blob: 2d31c700def0a7824676501619bc69277233f30e [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
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300754static int
755ensure_unicode(PyObject *obj)
756{
757 if (!PyUnicode_Check(obj)) {
758 PyErr_Format(PyExc_TypeError,
759 "must be str, not %.100s",
760 Py_TYPE(obj)->tp_name);
761 return -1;
762 }
763 return PyUnicode_READY(obj);
764}
765
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200766/* Compilation of templated routines */
767
768#include "stringlib/asciilib.h"
769#include "stringlib/fastsearch.h"
770#include "stringlib/partition.h"
771#include "stringlib/split.h"
772#include "stringlib/count.h"
773#include "stringlib/find.h"
774#include "stringlib/find_max_char.h"
775#include "stringlib/localeutil.h"
776#include "stringlib/undef.h"
777
778#include "stringlib/ucs1lib.h"
779#include "stringlib/fastsearch.h"
780#include "stringlib/partition.h"
781#include "stringlib/split.h"
782#include "stringlib/count.h"
783#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300784#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200785#include "stringlib/find_max_char.h"
786#include "stringlib/localeutil.h"
787#include "stringlib/undef.h"
788
789#include "stringlib/ucs2lib.h"
790#include "stringlib/fastsearch.h"
791#include "stringlib/partition.h"
792#include "stringlib/split.h"
793#include "stringlib/count.h"
794#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300795#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200796#include "stringlib/find_max_char.h"
797#include "stringlib/localeutil.h"
798#include "stringlib/undef.h"
799
800#include "stringlib/ucs4lib.h"
801#include "stringlib/fastsearch.h"
802#include "stringlib/partition.h"
803#include "stringlib/split.h"
804#include "stringlib/count.h"
805#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300806#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200807#include "stringlib/find_max_char.h"
808#include "stringlib/localeutil.h"
809#include "stringlib/undef.h"
810
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200811#include "stringlib/unicodedefs.h"
812#include "stringlib/fastsearch.h"
813#include "stringlib/count.h"
814#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100815#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200816
Guido van Rossumd57fd912000-03-10 22:53:23 +0000817/* --- Unicode Object ----------------------------------------------------- */
818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200820fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200822Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823 Py_ssize_t size, Py_UCS4 ch,
824 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200825{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200826 switch (kind) {
827 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200828 if ((Py_UCS1) ch != ch)
829 return -1;
830 if (direction > 0)
831 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
832 else
833 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200835 if ((Py_UCS2) ch != ch)
836 return -1;
837 if (direction > 0)
838 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
839 else
840 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200841 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200842 if (direction > 0)
843 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
844 else
845 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200846 default:
847 assert(0);
848 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200850}
851
Victor Stinnerafffce42012-10-03 23:03:17 +0200852#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000853/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200854 earlier.
855
856 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
857 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
858 invalid character in Unicode 6.0. */
859static void
860unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
861{
862 int kind = PyUnicode_KIND(unicode);
863 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
864 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
865 if (length <= old_length)
866 return;
867 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
868}
869#endif
870
Victor Stinnerfe226c02011-10-03 03:52:20 +0200871static PyObject*
872resize_compact(PyObject *unicode, Py_ssize_t length)
873{
874 Py_ssize_t char_size;
875 Py_ssize_t struct_size;
876 Py_ssize_t new_size;
877 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100878 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200879#ifdef Py_DEBUG
880 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
881#endif
882
Victor Stinner79891572012-05-03 13:43:07 +0200883 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200884 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100885 assert(PyUnicode_IS_COMPACT(unicode));
886
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200887 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100888 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200889 struct_size = sizeof(PyASCIIObject);
890 else
891 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200892 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200893
Victor Stinnerfe226c02011-10-03 03:52:20 +0200894 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
895 PyErr_NoMemory();
896 return NULL;
897 }
898 new_size = (struct_size + (length + 1) * char_size);
899
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200900 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
901 PyObject_DEL(_PyUnicode_UTF8(unicode));
902 _PyUnicode_UTF8(unicode) = NULL;
903 _PyUnicode_UTF8_LENGTH(unicode) = 0;
904 }
Victor Stinner84def372011-12-11 20:04:56 +0100905 _Py_DEC_REFTOTAL;
906 _Py_ForgetReference(unicode);
907
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300908 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100909 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100910 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200911 PyErr_NoMemory();
912 return NULL;
913 }
Victor Stinner84def372011-12-11 20:04:56 +0100914 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200915 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100916
Victor Stinnerfe226c02011-10-03 03:52:20 +0200917 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200918 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200919 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100920 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200921 _PyUnicode_WSTR_LENGTH(unicode) = length;
922 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100923 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
924 PyObject_DEL(_PyUnicode_WSTR(unicode));
925 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100926 if (!PyUnicode_IS_ASCII(unicode))
927 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100928 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200929#ifdef Py_DEBUG
930 unicode_fill_invalid(unicode, old_length);
931#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
933 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200934 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200935 return unicode;
936}
937
Alexander Belopolsky40018472011-02-26 01:02:56 +0000938static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200939resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000940{
Victor Stinner95663112011-10-04 01:03:50 +0200941 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100942 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200943 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200944 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000945
Victor Stinnerfe226c02011-10-03 03:52:20 +0200946 if (PyUnicode_IS_READY(unicode)) {
947 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200948 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200949 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200950#ifdef Py_DEBUG
951 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
952#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953
954 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200955 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200956 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
957 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200958
959 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
960 PyErr_NoMemory();
961 return -1;
962 }
963 new_size = (length + 1) * char_size;
964
Victor Stinner7a9105a2011-12-12 00:13:42 +0100965 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
966 {
967 PyObject_DEL(_PyUnicode_UTF8(unicode));
968 _PyUnicode_UTF8(unicode) = NULL;
969 _PyUnicode_UTF8_LENGTH(unicode) = 0;
970 }
971
Victor Stinnerfe226c02011-10-03 03:52:20 +0200972 data = (PyObject *)PyObject_REALLOC(data, new_size);
973 if (data == NULL) {
974 PyErr_NoMemory();
975 return -1;
976 }
977 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200978 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200980 _PyUnicode_WSTR_LENGTH(unicode) = length;
981 }
982 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200983 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200984 _PyUnicode_UTF8_LENGTH(unicode) = length;
985 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200986 _PyUnicode_LENGTH(unicode) = length;
987 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200988#ifdef Py_DEBUG
989 unicode_fill_invalid(unicode, old_length);
990#endif
Victor Stinner95663112011-10-04 01:03:50 +0200991 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200992 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200994 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200995 }
Victor Stinner95663112011-10-04 01:03:50 +0200996 assert(_PyUnicode_WSTR(unicode) != NULL);
997
998 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700999 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001000 PyErr_NoMemory();
1001 return -1;
1002 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001003 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001004 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001005 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001006 if (!wstr) {
1007 PyErr_NoMemory();
1008 return -1;
1009 }
1010 _PyUnicode_WSTR(unicode) = wstr;
1011 _PyUnicode_WSTR(unicode)[length] = 0;
1012 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001013 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001014 return 0;
1015}
1016
Victor Stinnerfe226c02011-10-03 03:52:20 +02001017static PyObject*
1018resize_copy(PyObject *unicode, Py_ssize_t length)
1019{
1020 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001021 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001022 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001023
Benjamin Petersonbac79492012-01-14 13:34:47 -05001024 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001025 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001026
1027 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1028 if (copy == NULL)
1029 return NULL;
1030
1031 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001032 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001033 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001034 }
1035 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001036 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001037
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001038 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001039 if (w == NULL)
1040 return NULL;
1041 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1042 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001043 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1044 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001045 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 }
1047}
1048
Guido van Rossumd57fd912000-03-10 22:53:23 +00001049/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001050 Ux0000 terminated; some code (e.g. new_identifier)
1051 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001052
1053 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001054 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001055
1056*/
1057
Alexander Belopolsky40018472011-02-26 01:02:56 +00001058static PyUnicodeObject *
1059_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001060{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001061 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001063
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001065 if (length == 0 && unicode_empty != NULL) {
1066 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001067 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001068 }
1069
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001070 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001071 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001072 return (PyUnicodeObject *)PyErr_NoMemory();
1073 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074 if (length < 0) {
1075 PyErr_SetString(PyExc_SystemError,
1076 "Negative size passed to _PyUnicode_New");
1077 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001078 }
1079
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001080 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1081 if (unicode == NULL)
1082 return NULL;
1083 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001084
1085 _PyUnicode_WSTR_LENGTH(unicode) = length;
1086 _PyUnicode_HASH(unicode) = -1;
1087 _PyUnicode_STATE(unicode).interned = 0;
1088 _PyUnicode_STATE(unicode).kind = 0;
1089 _PyUnicode_STATE(unicode).compact = 0;
1090 _PyUnicode_STATE(unicode).ready = 0;
1091 _PyUnicode_STATE(unicode).ascii = 0;
1092 _PyUnicode_DATA_ANY(unicode) = NULL;
1093 _PyUnicode_LENGTH(unicode) = 0;
1094 _PyUnicode_UTF8(unicode) = NULL;
1095 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001097 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1098 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001099 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001100 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001101 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001103
Jeremy Hyltond8082792003-09-16 19:41:39 +00001104 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001105 * the caller fails before initializing str -- unicode_resize()
1106 * reads str[0], and the Keep-Alive optimization can keep memory
1107 * allocated for str alive across a call to unicode_dealloc(unicode).
1108 * We don't want unicode_resize to read uninitialized memory in
1109 * that case.
1110 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111 _PyUnicode_WSTR(unicode)[0] = 0;
1112 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001113
Victor Stinner7931d9a2011-11-04 00:22:48 +01001114 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001115 return unicode;
1116}
1117
Victor Stinnerf42dc442011-10-02 23:33:16 +02001118static const char*
1119unicode_kind_name(PyObject *unicode)
1120{
Victor Stinner42dfd712011-10-03 14:41:45 +02001121 /* don't check consistency: unicode_kind_name() is called from
1122 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001123 if (!PyUnicode_IS_COMPACT(unicode))
1124 {
1125 if (!PyUnicode_IS_READY(unicode))
1126 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001127 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001128 {
1129 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001130 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001131 return "legacy ascii";
1132 else
1133 return "legacy latin1";
1134 case PyUnicode_2BYTE_KIND:
1135 return "legacy UCS2";
1136 case PyUnicode_4BYTE_KIND:
1137 return "legacy UCS4";
1138 default:
1139 return "<legacy invalid kind>";
1140 }
1141 }
1142 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001143 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001144 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001145 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001146 return "ascii";
1147 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001148 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001149 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001150 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001152 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001153 default:
1154 return "<invalid compact kind>";
1155 }
1156}
1157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001158#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159/* Functions wrapping macros for use in debugger */
1160char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001161 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001162}
1163
1164void *_PyUnicode_compact_data(void *unicode) {
1165 return _PyUnicode_COMPACT_DATA(unicode);
1166}
1167void *_PyUnicode_data(void *unicode){
1168 printf("obj %p\n", unicode);
1169 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1170 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1171 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1172 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1173 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1174 return PyUnicode_DATA(unicode);
1175}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001176
1177void
1178_PyUnicode_Dump(PyObject *op)
1179{
1180 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001181 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1182 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1183 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001184
Victor Stinnera849a4b2011-10-03 12:12:11 +02001185 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001186 {
1187 if (ascii->state.ascii)
1188 data = (ascii + 1);
1189 else
1190 data = (compact + 1);
1191 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001192 else
1193 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001194 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1195 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001196
Victor Stinnera849a4b2011-10-03 12:12:11 +02001197 if (ascii->wstr == data)
1198 printf("shared ");
1199 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001200
Victor Stinnera3b334d2011-10-03 13:53:37 +02001201 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001202 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001203 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1204 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001205 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1206 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001207 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001208 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001209}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210#endif
1211
1212PyObject *
1213PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1214{
1215 PyObject *obj;
1216 PyCompactUnicodeObject *unicode;
1217 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001218 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001219 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 Py_ssize_t char_size;
1221 Py_ssize_t struct_size;
1222
1223 /* Optimization for empty strings */
1224 if (size == 0 && unicode_empty != NULL) {
1225 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001226 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001227 }
1228
Victor Stinner9e9d6892011-10-04 01:02:02 +02001229 is_ascii = 0;
1230 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231 struct_size = sizeof(PyCompactUnicodeObject);
1232 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001233 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234 char_size = 1;
1235 is_ascii = 1;
1236 struct_size = sizeof(PyASCIIObject);
1237 }
1238 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001239 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 char_size = 1;
1241 }
1242 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001243 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001244 char_size = 2;
1245 if (sizeof(wchar_t) == 2)
1246 is_sharing = 1;
1247 }
1248 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001249 if (maxchar > MAX_UNICODE) {
1250 PyErr_SetString(PyExc_SystemError,
1251 "invalid maximum character passed to PyUnicode_New");
1252 return NULL;
1253 }
Victor Stinner8f825062012-04-27 13:55:39 +02001254 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001255 char_size = 4;
1256 if (sizeof(wchar_t) == 4)
1257 is_sharing = 1;
1258 }
1259
1260 /* Ensure we won't overflow the size. */
1261 if (size < 0) {
1262 PyErr_SetString(PyExc_SystemError,
1263 "Negative size passed to PyUnicode_New");
1264 return NULL;
1265 }
1266 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1267 return PyErr_NoMemory();
1268
1269 /* Duplicated allocation code from _PyObject_New() instead of a call to
1270 * PyObject_New() so we are able to allocate space for the object and
1271 * it's data buffer.
1272 */
1273 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1274 if (obj == NULL)
1275 return PyErr_NoMemory();
1276 obj = PyObject_INIT(obj, &PyUnicode_Type);
1277 if (obj == NULL)
1278 return NULL;
1279
1280 unicode = (PyCompactUnicodeObject *)obj;
1281 if (is_ascii)
1282 data = ((PyASCIIObject*)obj) + 1;
1283 else
1284 data = unicode + 1;
1285 _PyUnicode_LENGTH(unicode) = size;
1286 _PyUnicode_HASH(unicode) = -1;
1287 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001288 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001289 _PyUnicode_STATE(unicode).compact = 1;
1290 _PyUnicode_STATE(unicode).ready = 1;
1291 _PyUnicode_STATE(unicode).ascii = is_ascii;
1292 if (is_ascii) {
1293 ((char*)data)[size] = 0;
1294 _PyUnicode_WSTR(unicode) = NULL;
1295 }
Victor Stinner8f825062012-04-27 13:55:39 +02001296 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 ((char*)data)[size] = 0;
1298 _PyUnicode_WSTR(unicode) = NULL;
1299 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001300 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001301 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001303 else {
1304 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001305 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001306 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001308 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 ((Py_UCS4*)data)[size] = 0;
1310 if (is_sharing) {
1311 _PyUnicode_WSTR_LENGTH(unicode) = size;
1312 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1313 }
1314 else {
1315 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1316 _PyUnicode_WSTR(unicode) = NULL;
1317 }
1318 }
Victor Stinner8f825062012-04-27 13:55:39 +02001319#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001320 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001321#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001322 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 return obj;
1324}
1325
1326#if SIZEOF_WCHAR_T == 2
1327/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1328 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001329 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330
1331 This function assumes that unicode can hold one more code point than wstr
1332 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001333static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001335 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336{
1337 const wchar_t *iter;
1338 Py_UCS4 *ucs4_out;
1339
Victor Stinner910337b2011-10-03 03:20:16 +02001340 assert(unicode != NULL);
1341 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1343 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1344
1345 for (iter = begin; iter < end; ) {
1346 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1347 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001348 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1349 && (iter+1) < end
1350 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351 {
Victor Stinner551ac952011-11-29 22:58:13 +01001352 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353 iter += 2;
1354 }
1355 else {
1356 *ucs4_out++ = *iter;
1357 iter++;
1358 }
1359 }
1360 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1361 _PyUnicode_GET_LENGTH(unicode)));
1362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363}
1364#endif
1365
Victor Stinnercd9950f2011-10-02 00:34:53 +02001366static int
Victor Stinner488fa492011-12-12 00:01:39 +01001367unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001368{
Victor Stinner488fa492011-12-12 00:01:39 +01001369 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001370 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001371 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001372 return -1;
1373 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001374 return 0;
1375}
1376
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377static int
1378_copy_characters(PyObject *to, Py_ssize_t to_start,
1379 PyObject *from, Py_ssize_t from_start,
1380 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001382 unsigned int from_kind, to_kind;
1383 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001384
Victor Stinneree4544c2012-05-09 22:24:08 +02001385 assert(0 <= how_many);
1386 assert(0 <= from_start);
1387 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001388 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001389 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001390 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinnerd3f08822012-05-29 12:57:52 +02001392 assert(PyUnicode_Check(to));
1393 assert(PyUnicode_IS_READY(to));
1394 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1395
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001396 if (how_many == 0)
1397 return 0;
1398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001400 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001402 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403
Victor Stinnerf1852262012-06-16 16:38:26 +02001404#ifdef Py_DEBUG
1405 if (!check_maxchar
1406 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1407 {
1408 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1409 Py_UCS4 ch;
1410 Py_ssize_t i;
1411 for (i=0; i < how_many; i++) {
1412 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1413 assert(ch <= to_maxchar);
1414 }
1415 }
1416#endif
1417
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001418 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001419 if (check_maxchar
1420 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1421 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001422 /* Writing Latin-1 characters into an ASCII string requires to
1423 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001424 Py_UCS4 max_char;
1425 max_char = ucs1lib_find_max_char(from_data,
1426 (Py_UCS1*)from_data + how_many);
1427 if (max_char >= 128)
1428 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001429 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001430 Py_MEMCPY((char*)to_data + to_kind * to_start,
1431 (char*)from_data + from_kind * from_start,
1432 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001434 else if (from_kind == PyUnicode_1BYTE_KIND
1435 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001436 {
1437 _PyUnicode_CONVERT_BYTES(
1438 Py_UCS1, Py_UCS2,
1439 PyUnicode_1BYTE_DATA(from) + from_start,
1440 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1441 PyUnicode_2BYTE_DATA(to) + to_start
1442 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001443 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001444 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001445 && to_kind == PyUnicode_4BYTE_KIND)
1446 {
1447 _PyUnicode_CONVERT_BYTES(
1448 Py_UCS1, Py_UCS4,
1449 PyUnicode_1BYTE_DATA(from) + from_start,
1450 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1451 PyUnicode_4BYTE_DATA(to) + to_start
1452 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001453 }
1454 else if (from_kind == PyUnicode_2BYTE_KIND
1455 && to_kind == PyUnicode_4BYTE_KIND)
1456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS2, Py_UCS4,
1459 PyUnicode_2BYTE_DATA(from) + from_start,
1460 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_4BYTE_DATA(to) + to_start
1462 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001463 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001464 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001465 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1466
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001467 if (!check_maxchar) {
1468 if (from_kind == PyUnicode_2BYTE_KIND
1469 && to_kind == PyUnicode_1BYTE_KIND)
1470 {
1471 _PyUnicode_CONVERT_BYTES(
1472 Py_UCS2, Py_UCS1,
1473 PyUnicode_2BYTE_DATA(from) + from_start,
1474 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1475 PyUnicode_1BYTE_DATA(to) + to_start
1476 );
1477 }
1478 else if (from_kind == PyUnicode_4BYTE_KIND
1479 && to_kind == PyUnicode_1BYTE_KIND)
1480 {
1481 _PyUnicode_CONVERT_BYTES(
1482 Py_UCS4, Py_UCS1,
1483 PyUnicode_4BYTE_DATA(from) + from_start,
1484 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1485 PyUnicode_1BYTE_DATA(to) + to_start
1486 );
1487 }
1488 else if (from_kind == PyUnicode_4BYTE_KIND
1489 && to_kind == PyUnicode_2BYTE_KIND)
1490 {
1491 _PyUnicode_CONVERT_BYTES(
1492 Py_UCS4, Py_UCS2,
1493 PyUnicode_4BYTE_DATA(from) + from_start,
1494 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1495 PyUnicode_2BYTE_DATA(to) + to_start
1496 );
1497 }
1498 else {
1499 assert(0);
1500 return -1;
1501 }
1502 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001503 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001504 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001505 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001506 Py_ssize_t i;
1507
Victor Stinnera0702ab2011-09-29 14:14:38 +02001508 for (i=0; i < how_many; i++) {
1509 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001510 if (ch > to_maxchar)
1511 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001512 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1513 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001514 }
1515 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001516 return 0;
1517}
1518
Victor Stinnerd3f08822012-05-29 12:57:52 +02001519void
1520_PyUnicode_FastCopyCharacters(
1521 PyObject *to, Py_ssize_t to_start,
1522 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523{
1524 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1525}
1526
1527Py_ssize_t
1528PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start,
1530 Py_ssize_t how_many)
1531{
1532 int err;
1533
1534 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1535 PyErr_BadInternalCall();
1536 return -1;
1537 }
1538
Benjamin Petersonbac79492012-01-14 13:34:47 -05001539 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001540 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001541 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001542 return -1;
1543
Victor Stinnerd3f08822012-05-29 12:57:52 +02001544 if (from_start < 0) {
1545 PyErr_SetString(PyExc_IndexError, "string index out of range");
1546 return -1;
1547 }
1548 if (to_start < 0) {
1549 PyErr_SetString(PyExc_IndexError, "string index out of range");
1550 return -1;
1551 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001552 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1553 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1554 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001555 "Cannot write %zi characters at %zi "
1556 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001557 how_many, to_start, PyUnicode_GET_LENGTH(to));
1558 return -1;
1559 }
1560
1561 if (how_many == 0)
1562 return 0;
1563
Victor Stinner488fa492011-12-12 00:01:39 +01001564 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001565 return -1;
1566
1567 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1568 if (err) {
1569 PyErr_Format(PyExc_SystemError,
1570 "Cannot copy %s characters "
1571 "into a string of %s characters",
1572 unicode_kind_name(from),
1573 unicode_kind_name(to));
1574 return -1;
1575 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001576 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001577}
1578
Victor Stinner17222162011-09-28 22:15:37 +02001579/* Find the maximum code point and count the number of surrogate pairs so a
1580 correct string length can be computed before converting a string to UCS4.
1581 This function counts single surrogates as a character and not as a pair.
1582
1583 Return 0 on success, or -1 on error. */
1584static int
1585find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1586 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001587{
1588 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001589 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001590
Victor Stinnerc53be962011-10-02 21:33:54 +02001591 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 *num_surrogates = 0;
1593 *maxchar = 0;
1594
1595 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001596#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001597 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1598 && (iter+1) < end
1599 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1600 {
1601 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1602 ++(*num_surrogates);
1603 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604 }
1605 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001607 {
1608 ch = *iter;
1609 iter++;
1610 }
1611 if (ch > *maxchar) {
1612 *maxchar = ch;
1613 if (*maxchar > MAX_UNICODE) {
1614 PyErr_Format(PyExc_ValueError,
1615 "character U+%x is not in range [U+0000; U+10ffff]",
1616 ch);
1617 return -1;
1618 }
1619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001620 }
1621 return 0;
1622}
1623
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001624int
1625_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001626{
1627 wchar_t *end;
1628 Py_UCS4 maxchar = 0;
1629 Py_ssize_t num_surrogates;
1630#if SIZEOF_WCHAR_T == 2
1631 Py_ssize_t length_wo_surrogates;
1632#endif
1633
Georg Brandl7597add2011-10-05 16:36:47 +02001634 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001635 strings were created using _PyObject_New() and where no canonical
1636 representation (the str field) has been set yet aka strings
1637 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001638 assert(_PyUnicode_CHECK(unicode));
1639 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001640 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001641 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001642 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001643 /* Actually, it should neither be interned nor be anything else: */
1644 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001647 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001648 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001650
1651 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001652 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1653 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001654 PyErr_NoMemory();
1655 return -1;
1656 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001657 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 _PyUnicode_WSTR(unicode), end,
1659 PyUnicode_1BYTE_DATA(unicode));
1660 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1661 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1662 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1663 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001664 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001665 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001666 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001667 }
1668 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001669 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001670 _PyUnicode_UTF8(unicode) = NULL;
1671 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 }
1673 PyObject_FREE(_PyUnicode_WSTR(unicode));
1674 _PyUnicode_WSTR(unicode) = NULL;
1675 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1676 }
1677 /* In this case we might have to convert down from 4-byte native
1678 wchar_t to 2-byte unicode. */
1679 else if (maxchar < 65536) {
1680 assert(num_surrogates == 0 &&
1681 "FindMaxCharAndNumSurrogatePairs() messed up");
1682
Victor Stinner506f5922011-09-28 22:34:18 +02001683#if SIZEOF_WCHAR_T == 2
1684 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001685 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001686 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1687 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1688 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001689 _PyUnicode_UTF8(unicode) = NULL;
1690 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001691#else
1692 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001693 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001694 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001695 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001696 PyErr_NoMemory();
1697 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698 }
Victor Stinner506f5922011-09-28 22:34:18 +02001699 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1700 _PyUnicode_WSTR(unicode), end,
1701 PyUnicode_2BYTE_DATA(unicode));
1702 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1703 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1704 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001705 _PyUnicode_UTF8(unicode) = NULL;
1706 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001707 PyObject_FREE(_PyUnicode_WSTR(unicode));
1708 _PyUnicode_WSTR(unicode) = NULL;
1709 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1710#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001711 }
1712 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1713 else {
1714#if SIZEOF_WCHAR_T == 2
1715 /* in case the native representation is 2-bytes, we need to allocate a
1716 new normalized 4-byte version. */
1717 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001718 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1719 PyErr_NoMemory();
1720 return -1;
1721 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001722 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1723 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 PyErr_NoMemory();
1725 return -1;
1726 }
1727 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1728 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001729 _PyUnicode_UTF8(unicode) = NULL;
1730 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001731 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1732 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001733 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 PyObject_FREE(_PyUnicode_WSTR(unicode));
1735 _PyUnicode_WSTR(unicode) = NULL;
1736 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1737#else
1738 assert(num_surrogates == 0);
1739
Victor Stinnerc3c74152011-10-02 20:39:55 +02001740 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001741 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001742 _PyUnicode_UTF8(unicode) = NULL;
1743 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001744 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1745#endif
1746 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1747 }
1748 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001749 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 return 0;
1751}
1752
Alexander Belopolsky40018472011-02-26 01:02:56 +00001753static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001754unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001755{
Walter Dörwald16807132007-05-25 13:52:07 +00001756 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001757 case SSTATE_NOT_INTERNED:
1758 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001759
Benjamin Peterson29060642009-01-31 22:14:21 +00001760 case SSTATE_INTERNED_MORTAL:
1761 /* revive dead object temporarily for DelItem */
1762 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001763 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001764 Py_FatalError(
1765 "deletion of interned string failed");
1766 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001767
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_INTERNED_IMMORTAL:
1769 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001770
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 default:
1772 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001773 }
1774
Victor Stinner03490912011-10-03 23:45:12 +02001775 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001776 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001777 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001778 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001779 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1780 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001781
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001782 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001783}
1784
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001785#ifdef Py_DEBUG
1786static int
1787unicode_is_singleton(PyObject *unicode)
1788{
1789 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1790 if (unicode == unicode_empty)
1791 return 1;
1792 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1793 {
1794 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1795 if (ch < 256 && unicode_latin1[ch] == unicode)
1796 return 1;
1797 }
1798 return 0;
1799}
1800#endif
1801
Alexander Belopolsky40018472011-02-26 01:02:56 +00001802static int
Victor Stinner488fa492011-12-12 00:01:39 +01001803unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001804{
Victor Stinner488fa492011-12-12 00:01:39 +01001805 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001806 if (Py_REFCNT(unicode) != 1)
1807 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001808 if (_PyUnicode_HASH(unicode) != -1)
1809 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001810 if (PyUnicode_CHECK_INTERNED(unicode))
1811 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001812 if (!PyUnicode_CheckExact(unicode))
1813 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001814#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001815 /* singleton refcount is greater than 1 */
1816 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001817#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001818 return 1;
1819}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001820
Victor Stinnerfe226c02011-10-03 03:52:20 +02001821static int
1822unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1823{
1824 PyObject *unicode;
1825 Py_ssize_t old_length;
1826
1827 assert(p_unicode != NULL);
1828 unicode = *p_unicode;
1829
1830 assert(unicode != NULL);
1831 assert(PyUnicode_Check(unicode));
1832 assert(0 <= length);
1833
Victor Stinner910337b2011-10-03 03:20:16 +02001834 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001835 old_length = PyUnicode_WSTR_LENGTH(unicode);
1836 else
1837 old_length = PyUnicode_GET_LENGTH(unicode);
1838 if (old_length == length)
1839 return 0;
1840
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001841 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001842 _Py_INCREF_UNICODE_EMPTY();
1843 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001844 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001845 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001846 return 0;
1847 }
1848
Victor Stinner488fa492011-12-12 00:01:39 +01001849 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001850 PyObject *copy = resize_copy(unicode, length);
1851 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001852 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001853 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001854 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001855 }
1856
Victor Stinnerfe226c02011-10-03 03:52:20 +02001857 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001858 PyObject *new_unicode = resize_compact(unicode, length);
1859 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001860 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001861 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001862 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001863 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001864 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001865}
1866
Alexander Belopolsky40018472011-02-26 01:02:56 +00001867int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001868PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001869{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001870 PyObject *unicode;
1871 if (p_unicode == NULL) {
1872 PyErr_BadInternalCall();
1873 return -1;
1874 }
1875 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001876 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001877 {
1878 PyErr_BadInternalCall();
1879 return -1;
1880 }
1881 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001882}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001883
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001884/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001885
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001886 WARNING: The function doesn't copy the terminating null character and
1887 doesn't check the maximum character (may write a latin1 character in an
1888 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001889static void
1890unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1891 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001892{
1893 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1894 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001895 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001896
1897 switch (kind) {
1898 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001899 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001900#ifdef Py_DEBUG
1901 if (PyUnicode_IS_ASCII(unicode)) {
1902 Py_UCS4 maxchar = ucs1lib_find_max_char(
1903 (const Py_UCS1*)str,
1904 (const Py_UCS1*)str + len);
1905 assert(maxchar < 128);
1906 }
1907#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001908 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001909 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001910 }
1911 case PyUnicode_2BYTE_KIND: {
1912 Py_UCS2 *start = (Py_UCS2 *)data + index;
1913 Py_UCS2 *ucs2 = start;
1914 assert(index <= PyUnicode_GET_LENGTH(unicode));
1915
Victor Stinner184252a2012-06-16 02:57:41 +02001916 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001917 *ucs2 = (Py_UCS2)*str;
1918
1919 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001920 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001921 }
1922 default: {
1923 Py_UCS4 *start = (Py_UCS4 *)data + index;
1924 Py_UCS4 *ucs4 = start;
1925 assert(kind == PyUnicode_4BYTE_KIND);
1926 assert(index <= PyUnicode_GET_LENGTH(unicode));
1927
Victor Stinner184252a2012-06-16 02:57:41 +02001928 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001929 *ucs4 = (Py_UCS4)*str;
1930
1931 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001932 }
1933 }
1934}
1935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001936static PyObject*
1937get_latin1_char(unsigned char ch)
1938{
Victor Stinnera464fc12011-10-02 20:39:30 +02001939 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001940 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001941 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001942 if (!unicode)
1943 return NULL;
1944 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001945 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946 unicode_latin1[ch] = unicode;
1947 }
1948 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001949 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950}
1951
Victor Stinner985a82a2014-01-03 12:53:47 +01001952static PyObject*
1953unicode_char(Py_UCS4 ch)
1954{
1955 PyObject *unicode;
1956
1957 assert(ch <= MAX_UNICODE);
1958
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001959 if (ch < 256)
1960 return get_latin1_char(ch);
1961
Victor Stinner985a82a2014-01-03 12:53:47 +01001962 unicode = PyUnicode_New(1, ch);
1963 if (unicode == NULL)
1964 return NULL;
1965 switch (PyUnicode_KIND(unicode)) {
1966 case PyUnicode_1BYTE_KIND:
1967 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1968 break;
1969 case PyUnicode_2BYTE_KIND:
1970 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1971 break;
1972 default:
1973 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1974 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1975 }
1976 assert(_PyUnicode_CheckConsistency(unicode, 1));
1977 return unicode;
1978}
1979
Alexander Belopolsky40018472011-02-26 01:02:56 +00001980PyObject *
1981PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001982{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001983 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984 Py_UCS4 maxchar = 0;
1985 Py_ssize_t num_surrogates;
1986
1987 if (u == NULL)
1988 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001989
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001990 /* If the Unicode data is known at construction time, we can apply
1991 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001993 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001994 if (size == 0)
1995 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997 /* Single character Unicode objects in the Latin-1 range are
1998 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001999 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 return get_latin1_char((unsigned char)*u);
2001
2002 /* If not empty and not single character, copy the Unicode data
2003 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002004 if (find_maxchar_surrogates(u, u + size,
2005 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002006 return NULL;
2007
Victor Stinner8faf8212011-12-08 22:14:11 +01002008 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002009 if (!unicode)
2010 return NULL;
2011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 switch (PyUnicode_KIND(unicode)) {
2013 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002014 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002015 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2016 break;
2017 case PyUnicode_2BYTE_KIND:
2018#if Py_UNICODE_SIZE == 2
2019 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2020#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002021 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2023#endif
2024 break;
2025 case PyUnicode_4BYTE_KIND:
2026#if SIZEOF_WCHAR_T == 2
2027 /* This is the only case which has to process surrogates, thus
2028 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002029 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030#else
2031 assert(num_surrogates == 0);
2032 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2033#endif
2034 break;
2035 default:
2036 assert(0 && "Impossible state");
2037 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002038
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002039 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002040}
2041
Alexander Belopolsky40018472011-02-26 01:02:56 +00002042PyObject *
2043PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002044{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002045 if (size < 0) {
2046 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002047 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002048 return NULL;
2049 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002050 if (u != NULL)
2051 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2052 else
2053 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002054}
2055
Alexander Belopolsky40018472011-02-26 01:02:56 +00002056PyObject *
2057PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002058{
2059 size_t size = strlen(u);
2060 if (size > PY_SSIZE_T_MAX) {
2061 PyErr_SetString(PyExc_OverflowError, "input too long");
2062 return NULL;
2063 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002064 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002065}
2066
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002067PyObject *
2068_PyUnicode_FromId(_Py_Identifier *id)
2069{
2070 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002071 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2072 strlen(id->string),
2073 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002074 if (!id->object)
2075 return NULL;
2076 PyUnicode_InternInPlace(&id->object);
2077 assert(!id->next);
2078 id->next = static_strings;
2079 static_strings = id;
2080 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081 return id->object;
2082}
2083
2084void
2085_PyUnicode_ClearStaticStrings()
2086{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002087 _Py_Identifier *tmp, *s = static_strings;
2088 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002089 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002090 tmp = s->next;
2091 s->next = NULL;
2092 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002093 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002094 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002095}
2096
Benjamin Peterson0df54292012-03-26 14:50:32 -04002097/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002098
Victor Stinnerd3f08822012-05-29 12:57:52 +02002099PyObject*
2100_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002101{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002102 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002103 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002104 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002105#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002106 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002107#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002108 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002109 }
Victor Stinner785938e2011-12-11 20:09:03 +01002110 unicode = PyUnicode_New(size, 127);
2111 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002112 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002113 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2114 assert(_PyUnicode_CheckConsistency(unicode, 1));
2115 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002116}
2117
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002118static Py_UCS4
2119kind_maxchar_limit(unsigned int kind)
2120{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002121 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002122 case PyUnicode_1BYTE_KIND:
2123 return 0x80;
2124 case PyUnicode_2BYTE_KIND:
2125 return 0x100;
2126 case PyUnicode_4BYTE_KIND:
2127 return 0x10000;
2128 default:
2129 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002130 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002131 }
2132}
2133
Victor Stinnere6abb482012-05-02 01:15:40 +02002134Py_LOCAL_INLINE(Py_UCS4)
2135align_maxchar(Py_UCS4 maxchar)
2136{
2137 if (maxchar <= 127)
2138 return 127;
2139 else if (maxchar <= 255)
2140 return 255;
2141 else if (maxchar <= 65535)
2142 return 65535;
2143 else
2144 return MAX_UNICODE;
2145}
2146
Victor Stinner702c7342011-10-05 13:50:52 +02002147static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002148_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002149{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002150 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002151 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002152
Serhiy Storchaka678db842013-01-26 12:16:36 +02002153 if (size == 0)
2154 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002155 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002156 if (size == 1)
2157 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002158
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002159 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002160 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002161 if (!res)
2162 return NULL;
2163 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002164 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002165 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002166}
2167
Victor Stinnere57b1c02011-09-28 22:20:48 +02002168static PyObject*
2169_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170{
2171 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002172 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002173
Serhiy Storchaka678db842013-01-26 12:16:36 +02002174 if (size == 0)
2175 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002176 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002177 if (size == 1)
2178 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002179
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002180 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002181 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002182 if (!res)
2183 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002184 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002186 else {
2187 _PyUnicode_CONVERT_BYTES(
2188 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2189 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002190 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002191 return res;
2192}
2193
Victor Stinnere57b1c02011-09-28 22:20:48 +02002194static PyObject*
2195_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002196{
2197 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002198 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002199
Serhiy Storchaka678db842013-01-26 12:16:36 +02002200 if (size == 0)
2201 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002202 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002203 if (size == 1)
2204 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002205
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002206 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002207 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208 if (!res)
2209 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002210 if (max_char < 256)
2211 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2212 PyUnicode_1BYTE_DATA(res));
2213 else if (max_char < 0x10000)
2214 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2215 PyUnicode_2BYTE_DATA(res));
2216 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002218 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002219 return res;
2220}
2221
2222PyObject*
2223PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2224{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002225 if (size < 0) {
2226 PyErr_SetString(PyExc_ValueError, "size must be positive");
2227 return NULL;
2228 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002229 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002230 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002231 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002233 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002235 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002236 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002237 PyErr_SetString(PyExc_SystemError, "invalid kind");
2238 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240}
2241
Victor Stinnerece58de2012-04-23 23:36:38 +02002242Py_UCS4
2243_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2244{
2245 enum PyUnicode_Kind kind;
2246 void *startptr, *endptr;
2247
2248 assert(PyUnicode_IS_READY(unicode));
2249 assert(0 <= start);
2250 assert(end <= PyUnicode_GET_LENGTH(unicode));
2251 assert(start <= end);
2252
2253 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2254 return PyUnicode_MAX_CHAR_VALUE(unicode);
2255
2256 if (start == end)
2257 return 127;
2258
Victor Stinner94d558b2012-04-27 22:26:58 +02002259 if (PyUnicode_IS_ASCII(unicode))
2260 return 127;
2261
Victor Stinnerece58de2012-04-23 23:36:38 +02002262 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002263 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002264 endptr = (char *)startptr + end * kind;
2265 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002266 switch(kind) {
2267 case PyUnicode_1BYTE_KIND:
2268 return ucs1lib_find_max_char(startptr, endptr);
2269 case PyUnicode_2BYTE_KIND:
2270 return ucs2lib_find_max_char(startptr, endptr);
2271 case PyUnicode_4BYTE_KIND:
2272 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002273 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002274 assert(0);
2275 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002276 }
2277}
2278
Victor Stinner25a4b292011-10-06 12:31:55 +02002279/* Ensure that a string uses the most efficient storage, if it is not the
2280 case: create a new string with of the right kind. Write NULL into *p_unicode
2281 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002282static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002283unicode_adjust_maxchar(PyObject **p_unicode)
2284{
2285 PyObject *unicode, *copy;
2286 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002287 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002288 unsigned int kind;
2289
2290 assert(p_unicode != NULL);
2291 unicode = *p_unicode;
2292 assert(PyUnicode_IS_READY(unicode));
2293 if (PyUnicode_IS_ASCII(unicode))
2294 return;
2295
2296 len = PyUnicode_GET_LENGTH(unicode);
2297 kind = PyUnicode_KIND(unicode);
2298 if (kind == PyUnicode_1BYTE_KIND) {
2299 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002300 max_char = ucs1lib_find_max_char(u, u + len);
2301 if (max_char >= 128)
2302 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002303 }
2304 else if (kind == PyUnicode_2BYTE_KIND) {
2305 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002306 max_char = ucs2lib_find_max_char(u, u + len);
2307 if (max_char >= 256)
2308 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002309 }
2310 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002311 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002312 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 max_char = ucs4lib_find_max_char(u, u + len);
2314 if (max_char >= 0x10000)
2315 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002316 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002317 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002318 if (copy != NULL)
2319 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002320 Py_DECREF(unicode);
2321 *p_unicode = copy;
2322}
2323
Victor Stinner034f6cf2011-09-30 02:26:44 +02002324PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002325_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002326{
Victor Stinner87af4f22011-11-21 23:03:47 +01002327 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002328 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002329
Victor Stinner034f6cf2011-09-30 02:26:44 +02002330 if (!PyUnicode_Check(unicode)) {
2331 PyErr_BadInternalCall();
2332 return NULL;
2333 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002334 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002335 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002336
Victor Stinner87af4f22011-11-21 23:03:47 +01002337 length = PyUnicode_GET_LENGTH(unicode);
2338 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002339 if (!copy)
2340 return NULL;
2341 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2342
Victor Stinner87af4f22011-11-21 23:03:47 +01002343 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2344 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002345 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002346 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002347}
2348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002349
Victor Stinnerbc603d12011-10-02 01:00:40 +02002350/* Widen Unicode objects to larger buffers. Don't write terminating null
2351 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002352
2353void*
2354_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2355{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002356 Py_ssize_t len;
2357 void *result;
2358 unsigned int skind;
2359
Benjamin Petersonbac79492012-01-14 13:34:47 -05002360 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002361 return NULL;
2362
2363 len = PyUnicode_GET_LENGTH(s);
2364 skind = PyUnicode_KIND(s);
2365 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002366 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002367 return NULL;
2368 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002369 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002370 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002371 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002372 if (!result)
2373 return PyErr_NoMemory();
2374 assert(skind == PyUnicode_1BYTE_KIND);
2375 _PyUnicode_CONVERT_BYTES(
2376 Py_UCS1, Py_UCS2,
2377 PyUnicode_1BYTE_DATA(s),
2378 PyUnicode_1BYTE_DATA(s) + len,
2379 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002380 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002381 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002382 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002383 if (!result)
2384 return PyErr_NoMemory();
2385 if (skind == PyUnicode_2BYTE_KIND) {
2386 _PyUnicode_CONVERT_BYTES(
2387 Py_UCS2, Py_UCS4,
2388 PyUnicode_2BYTE_DATA(s),
2389 PyUnicode_2BYTE_DATA(s) + len,
2390 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002392 else {
2393 assert(skind == PyUnicode_1BYTE_KIND);
2394 _PyUnicode_CONVERT_BYTES(
2395 Py_UCS1, Py_UCS4,
2396 PyUnicode_1BYTE_DATA(s),
2397 PyUnicode_1BYTE_DATA(s) + len,
2398 result);
2399 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002400 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002401 default:
2402 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 }
Victor Stinner01698042011-10-04 00:04:26 +02002404 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002405 return NULL;
2406}
2407
2408static Py_UCS4*
2409as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2410 int copy_null)
2411{
2412 int kind;
2413 void *data;
2414 Py_ssize_t len, targetlen;
2415 if (PyUnicode_READY(string) == -1)
2416 return NULL;
2417 kind = PyUnicode_KIND(string);
2418 data = PyUnicode_DATA(string);
2419 len = PyUnicode_GET_LENGTH(string);
2420 targetlen = len;
2421 if (copy_null)
2422 targetlen++;
2423 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002424 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002425 if (!target) {
2426 PyErr_NoMemory();
2427 return NULL;
2428 }
2429 }
2430 else {
2431 if (targetsize < targetlen) {
2432 PyErr_Format(PyExc_SystemError,
2433 "string is longer than the buffer");
2434 if (copy_null && 0 < targetsize)
2435 target[0] = 0;
2436 return NULL;
2437 }
2438 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002439 if (kind == PyUnicode_1BYTE_KIND) {
2440 Py_UCS1 *start = (Py_UCS1 *) data;
2441 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002443 else if (kind == PyUnicode_2BYTE_KIND) {
2444 Py_UCS2 *start = (Py_UCS2 *) data;
2445 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2446 }
2447 else {
2448 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002450 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 if (copy_null)
2452 target[len] = 0;
2453 return target;
2454}
2455
2456Py_UCS4*
2457PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2458 int copy_null)
2459{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002460 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 PyErr_BadInternalCall();
2462 return NULL;
2463 }
2464 return as_ucs4(string, target, targetsize, copy_null);
2465}
2466
2467Py_UCS4*
2468PyUnicode_AsUCS4Copy(PyObject *string)
2469{
2470 return as_ucs4(string, NULL, 0, 1);
2471}
2472
2473#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002474
Alexander Belopolsky40018472011-02-26 01:02:56 +00002475PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002476PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002477{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002478 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002479 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002480 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002481 PyErr_BadInternalCall();
2482 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002483 }
2484
Martin v. Löwis790465f2008-04-05 20:41:37 +00002485 if (size == -1) {
2486 size = wcslen(w);
2487 }
2488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002490}
2491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002493
Victor Stinner15a11362012-10-06 23:48:20 +02002494/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002495 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2496 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2497#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002498
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002499static int
2500unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2501 Py_ssize_t width, Py_ssize_t precision)
2502{
2503 Py_ssize_t length, fill, arglen;
2504 Py_UCS4 maxchar;
2505
2506 if (PyUnicode_READY(str) == -1)
2507 return -1;
2508
2509 length = PyUnicode_GET_LENGTH(str);
2510 if ((precision == -1 || precision >= length)
2511 && width <= length)
2512 return _PyUnicodeWriter_WriteStr(writer, str);
2513
2514 if (precision != -1)
2515 length = Py_MIN(precision, length);
2516
2517 arglen = Py_MAX(length, width);
2518 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2519 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2520 else
2521 maxchar = writer->maxchar;
2522
2523 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2524 return -1;
2525
2526 if (width > length) {
2527 fill = width - length;
2528 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2529 return -1;
2530 writer->pos += fill;
2531 }
2532
2533 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2534 str, 0, length);
2535 writer->pos += length;
2536 return 0;
2537}
2538
2539static int
2540unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2541 Py_ssize_t width, Py_ssize_t precision)
2542{
2543 /* UTF-8 */
2544 Py_ssize_t length;
2545 PyObject *unicode;
2546 int res;
2547
2548 length = strlen(str);
2549 if (precision != -1)
2550 length = Py_MIN(length, precision);
2551 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2552 if (unicode == NULL)
2553 return -1;
2554
2555 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2556 Py_DECREF(unicode);
2557 return res;
2558}
2559
Victor Stinner96865452011-03-01 23:44:09 +00002560static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002561unicode_fromformat_arg(_PyUnicodeWriter *writer,
2562 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002563{
Victor Stinnere215d962012-10-06 23:03:36 +02002564 const char *p;
2565 Py_ssize_t len;
2566 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002567 Py_ssize_t width;
2568 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002569 int longflag;
2570 int longlongflag;
2571 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002573
2574 p = f;
2575 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002576 zeropad = 0;
2577 if (*f == '0') {
2578 zeropad = 1;
2579 f++;
2580 }
Victor Stinner96865452011-03-01 23:44:09 +00002581
2582 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002583 width = -1;
2584 if (Py_ISDIGIT((unsigned)*f)) {
2585 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002586 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002587 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002589 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002590 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002591 return NULL;
2592 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002594 f++;
2595 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002596 }
2597 precision = -1;
2598 if (*f == '.') {
2599 f++;
2600 if (Py_ISDIGIT((unsigned)*f)) {
2601 precision = (*f - '0');
2602 f++;
2603 while (Py_ISDIGIT((unsigned)*f)) {
2604 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2605 PyErr_SetString(PyExc_ValueError,
2606 "precision too big");
2607 return NULL;
2608 }
2609 precision = (precision * 10) + (*f - '0');
2610 f++;
2611 }
2612 }
Victor Stinner96865452011-03-01 23:44:09 +00002613 if (*f == '%') {
2614 /* "%.3%s" => f points to "3" */
2615 f--;
2616 }
2617 }
2618 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002619 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002620 f--;
2621 }
Victor Stinner96865452011-03-01 23:44:09 +00002622
2623 /* Handle %ld, %lu, %lld and %llu. */
2624 longflag = 0;
2625 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002626 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002627 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002628 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002629 longflag = 1;
2630 ++f;
2631 }
2632#ifdef HAVE_LONG_LONG
2633 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002634 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002635 longlongflag = 1;
2636 f += 2;
2637 }
2638#endif
2639 }
2640 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002641 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002642 size_tflag = 1;
2643 ++f;
2644 }
Victor Stinnere215d962012-10-06 23:03:36 +02002645
2646 if (f[1] == '\0')
2647 writer->overallocate = 0;
2648
2649 switch (*f) {
2650 case 'c':
2651 {
2652 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002653 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002654 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002655 "character argument not in range(0x110000)");
2656 return NULL;
2657 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002658 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002659 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002660 break;
2661 }
2662
2663 case 'i':
2664 case 'd':
2665 case 'u':
2666 case 'x':
2667 {
2668 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002669 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002670 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002671
2672 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002673 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002674 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002675 va_arg(*vargs, unsigned long));
2676#ifdef HAVE_LONG_LONG
2677 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002678 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002679 va_arg(*vargs, unsigned PY_LONG_LONG));
2680#endif
2681 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002682 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002683 va_arg(*vargs, size_t));
2684 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002685 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002686 va_arg(*vargs, unsigned int));
2687 }
2688 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002689 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002690 }
2691 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002692 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002693 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002694 va_arg(*vargs, long));
2695#ifdef HAVE_LONG_LONG
2696 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002697 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002698 va_arg(*vargs, PY_LONG_LONG));
2699#endif
2700 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002701 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002702 va_arg(*vargs, Py_ssize_t));
2703 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002704 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002705 va_arg(*vargs, int));
2706 }
2707 assert(len >= 0);
2708
Victor Stinnere215d962012-10-06 23:03:36 +02002709 if (precision < len)
2710 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002711
2712 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002713 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2714 return NULL;
2715
Victor Stinnere215d962012-10-06 23:03:36 +02002716 if (width > precision) {
2717 Py_UCS4 fillchar;
2718 fill = width - precision;
2719 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002720 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2721 return NULL;
2722 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002723 }
Victor Stinner15a11362012-10-06 23:48:20 +02002724 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002725 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002726 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2727 return NULL;
2728 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002729 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002730
Victor Stinner4a587072013-11-19 12:54:53 +01002731 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2732 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002733 break;
2734 }
2735
2736 case 'p':
2737 {
2738 char number[MAX_LONG_LONG_CHARS];
2739
2740 len = sprintf(number, "%p", va_arg(*vargs, void*));
2741 assert(len >= 0);
2742
2743 /* %p is ill-defined: ensure leading 0x. */
2744 if (number[1] == 'X')
2745 number[1] = 'x';
2746 else if (number[1] != 'x') {
2747 memmove(number + 2, number,
2748 strlen(number) + 1);
2749 number[0] = '0';
2750 number[1] = 'x';
2751 len += 2;
2752 }
2753
Victor Stinner4a587072013-11-19 12:54:53 +01002754 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002755 return NULL;
2756 break;
2757 }
2758
2759 case 's':
2760 {
2761 /* UTF-8 */
2762 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002763 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002764 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002765 break;
2766 }
2767
2768 case 'U':
2769 {
2770 PyObject *obj = va_arg(*vargs, PyObject *);
2771 assert(obj && _PyUnicode_CHECK(obj));
2772
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002773 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002774 return NULL;
2775 break;
2776 }
2777
2778 case 'V':
2779 {
2780 PyObject *obj = va_arg(*vargs, PyObject *);
2781 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002782 if (obj) {
2783 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002784 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002785 return NULL;
2786 }
2787 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002788 assert(str != NULL);
2789 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002790 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002791 }
2792 break;
2793 }
2794
2795 case 'S':
2796 {
2797 PyObject *obj = va_arg(*vargs, PyObject *);
2798 PyObject *str;
2799 assert(obj);
2800 str = PyObject_Str(obj);
2801 if (!str)
2802 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002803 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002804 Py_DECREF(str);
2805 return NULL;
2806 }
2807 Py_DECREF(str);
2808 break;
2809 }
2810
2811 case 'R':
2812 {
2813 PyObject *obj = va_arg(*vargs, PyObject *);
2814 PyObject *repr;
2815 assert(obj);
2816 repr = PyObject_Repr(obj);
2817 if (!repr)
2818 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002819 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002820 Py_DECREF(repr);
2821 return NULL;
2822 }
2823 Py_DECREF(repr);
2824 break;
2825 }
2826
2827 case 'A':
2828 {
2829 PyObject *obj = va_arg(*vargs, PyObject *);
2830 PyObject *ascii;
2831 assert(obj);
2832 ascii = PyObject_ASCII(obj);
2833 if (!ascii)
2834 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002835 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002836 Py_DECREF(ascii);
2837 return NULL;
2838 }
2839 Py_DECREF(ascii);
2840 break;
2841 }
2842
2843 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002844 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002845 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002846 break;
2847
2848 default:
2849 /* if we stumble upon an unknown formatting code, copy the rest
2850 of the format string to the output string. (we cannot just
2851 skip the code, since there's no way to know what's in the
2852 argument list) */
2853 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002854 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002855 return NULL;
2856 f = p+len;
2857 return f;
2858 }
2859
2860 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002861 return f;
2862}
2863
Walter Dörwaldd2034312007-05-18 16:29:38 +00002864PyObject *
2865PyUnicode_FromFormatV(const char *format, va_list vargs)
2866{
Victor Stinnere215d962012-10-06 23:03:36 +02002867 va_list vargs2;
2868 const char *f;
2869 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002870
Victor Stinner8f674cc2013-04-17 23:02:17 +02002871 _PyUnicodeWriter_Init(&writer);
2872 writer.min_length = strlen(format) + 100;
2873 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002874
2875 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2876 Copy it to be able to pass a reference to a subfunction. */
2877 Py_VA_COPY(vargs2, vargs);
2878
2879 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002880 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002881 f = unicode_fromformat_arg(&writer, f, &vargs2);
2882 if (f == NULL)
2883 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002884 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002886 const char *p;
2887 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002888
Victor Stinnere215d962012-10-06 23:03:36 +02002889 p = f;
2890 do
2891 {
2892 if ((unsigned char)*p > 127) {
2893 PyErr_Format(PyExc_ValueError,
2894 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2895 "string, got a non-ASCII byte: 0x%02x",
2896 (unsigned char)*p);
2897 return NULL;
2898 }
2899 p++;
2900 }
2901 while (*p != '\0' && *p != '%');
2902 len = p - f;
2903
2904 if (*p == '\0')
2905 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002906
2907 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002908 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002909
2910 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002911 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002912 }
Victor Stinnere215d962012-10-06 23:03:36 +02002913 return _PyUnicodeWriter_Finish(&writer);
2914
2915 fail:
2916 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918}
2919
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920PyObject *
2921PyUnicode_FromFormat(const char *format, ...)
2922{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002923 PyObject* ret;
2924 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
2926#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002927 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 ret = PyUnicode_FromFormatV(format, vargs);
2932 va_end(vargs);
2933 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002934}
2935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936#ifdef HAVE_WCHAR_H
2937
Victor Stinner5593d8a2010-10-02 11:11:27 +00002938/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2939 convert a Unicode object to a wide character string.
2940
Victor Stinnerd88d9832011-09-06 02:00:05 +02002941 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002942 character) required to convert the unicode object. Ignore size argument.
2943
Victor Stinnerd88d9832011-09-06 02:00:05 +02002944 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002946 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002947static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002948unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002949 wchar_t *w,
2950 Py_ssize_t size)
2951{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002952 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002953 const wchar_t *wstr;
2954
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002955 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002956 if (wstr == NULL)
2957 return -1;
2958
Victor Stinner5593d8a2010-10-02 11:11:27 +00002959 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002960 if (size > res)
2961 size = res + 1;
2962 else
2963 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002964 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002965 return res;
2966 }
2967 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002968 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002969}
2970
2971Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002972PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002973 wchar_t *w,
2974 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002975{
2976 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002977 PyErr_BadInternalCall();
2978 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002979 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002980 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002981}
2982
Victor Stinner137c34c2010-09-29 10:25:54 +00002983wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002984PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002985 Py_ssize_t *size)
2986{
2987 wchar_t* buffer;
2988 Py_ssize_t buflen;
2989
2990 if (unicode == NULL) {
2991 PyErr_BadInternalCall();
2992 return NULL;
2993 }
2994
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002995 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002996 if (buflen == -1)
2997 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002998 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002999 if (buffer == NULL) {
3000 PyErr_NoMemory();
3001 return NULL;
3002 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003003 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003004 if (buflen == -1) {
3005 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003006 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003007 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003008 if (size != NULL)
3009 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003010 return buffer;
3011}
3012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003013#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014
Alexander Belopolsky40018472011-02-26 01:02:56 +00003015PyObject *
3016PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003017{
Victor Stinner8faf8212011-12-08 22:14:11 +01003018 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 PyErr_SetString(PyExc_ValueError,
3020 "chr() arg not in range(0x110000)");
3021 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003022 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003023
Victor Stinner985a82a2014-01-03 12:53:47 +01003024 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003025}
3026
Alexander Belopolsky40018472011-02-26 01:02:56 +00003027PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003028PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003029{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003030 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003031 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003033 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003034 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003035 Py_INCREF(obj);
3036 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 }
3038 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003039 /* For a Unicode subtype that's not a Unicode object,
3040 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003041 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003042 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003043 PyErr_Format(PyExc_TypeError,
3044 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003045 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003046 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003047}
3048
Alexander Belopolsky40018472011-02-26 01:02:56 +00003049PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003050PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003051 const char *encoding,
3052 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003053{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003054 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003055 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003056
Guido van Rossumd57fd912000-03-10 22:53:23 +00003057 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003058 PyErr_BadInternalCall();
3059 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003061
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003062 /* Decoding bytes objects is the most common case and should be fast */
3063 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003064 if (PyBytes_GET_SIZE(obj) == 0)
3065 _Py_RETURN_UNICODE_EMPTY();
3066 v = PyUnicode_Decode(
3067 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3068 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003069 return v;
3070 }
3071
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003073 PyErr_SetString(PyExc_TypeError,
3074 "decoding str is not supported");
3075 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003076 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003077
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003078 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3079 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3080 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003081 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003082 Py_TYPE(obj)->tp_name);
3083 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003084 }
Tim Petersced69f82003-09-16 20:30:58 +00003085
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003086 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003087 PyBuffer_Release(&buffer);
3088 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003090
Serhiy Storchaka05997252013-01-26 12:14:02 +02003091 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003092 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003093 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003094}
3095
Victor Stinner600d3be2010-06-10 12:00:55 +00003096/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003097 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3098 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003099int
3100_Py_normalize_encoding(const char *encoding,
3101 char *lower,
3102 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003103{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003104 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003105 char *l;
3106 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003107
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003108 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01003109 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01003110 if (lower_len < 6)
3111 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003112 strcpy(lower, "utf-8");
3113 return 1;
3114 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003115 e = encoding;
3116 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003117 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003118 while (*e) {
3119 if (l == l_end)
3120 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003121 if (Py_ISUPPER(*e)) {
3122 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003123 }
3124 else if (*e == '_') {
3125 *l++ = '-';
3126 e++;
3127 }
3128 else {
3129 *l++ = *e++;
3130 }
3131 }
3132 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003133 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003134}
3135
Alexander Belopolsky40018472011-02-26 01:02:56 +00003136PyObject *
3137PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003138 Py_ssize_t size,
3139 const char *encoding,
3140 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003141{
3142 PyObject *buffer = NULL, *unicode;
3143 Py_buffer info;
3144 char lower[11]; /* Enough for any encoding shortcut */
3145
Fred Drakee4315f52000-05-09 19:53:39 +00003146 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003147 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003148 if ((strcmp(lower, "utf-8") == 0) ||
3149 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003150 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003151 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003152 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003153 (strcmp(lower, "iso-8859-1") == 0) ||
3154 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003155 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003156#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003157 else if (strcmp(lower, "mbcs") == 0)
3158 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003159#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003160 else if (strcmp(lower, "ascii") == 0)
3161 return PyUnicode_DecodeASCII(s, size, errors);
3162 else if (strcmp(lower, "utf-16") == 0)
3163 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3164 else if (strcmp(lower, "utf-32") == 0)
3165 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3166 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003167
3168 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003169 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003170 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003171 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003172 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003173 if (buffer == NULL)
3174 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003175 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003176 if (unicode == NULL)
3177 goto onError;
3178 if (!PyUnicode_Check(unicode)) {
3179 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003180 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3181 "use codecs.decode() to decode to arbitrary types",
3182 encoding,
3183 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003184 Py_DECREF(unicode);
3185 goto onError;
3186 }
3187 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003188 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003189
Benjamin Peterson29060642009-01-31 22:14:21 +00003190 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003191 Py_XDECREF(buffer);
3192 return NULL;
3193}
3194
Alexander Belopolsky40018472011-02-26 01:02:56 +00003195PyObject *
3196PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003197 const char *encoding,
3198 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003199{
3200 PyObject *v;
3201
3202 if (!PyUnicode_Check(unicode)) {
3203 PyErr_BadArgument();
3204 goto onError;
3205 }
3206
3207 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003208 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003209
3210 /* Decode via the codec registry */
3211 v = PyCodec_Decode(unicode, encoding, errors);
3212 if (v == NULL)
3213 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003214 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003215
Benjamin Peterson29060642009-01-31 22:14:21 +00003216 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003217 return NULL;
3218}
3219
Alexander Belopolsky40018472011-02-26 01:02:56 +00003220PyObject *
3221PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003222 const char *encoding,
3223 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003224{
3225 PyObject *v;
3226
3227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
3229 goto onError;
3230 }
3231
3232 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003233 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003234
3235 /* Decode via the codec registry */
3236 v = PyCodec_Decode(unicode, encoding, errors);
3237 if (v == NULL)
3238 goto onError;
3239 if (!PyUnicode_Check(v)) {
3240 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003241 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3242 "use codecs.decode() to decode to arbitrary types",
3243 encoding,
3244 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003245 Py_DECREF(v);
3246 goto onError;
3247 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003248 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003249
Benjamin Peterson29060642009-01-31 22:14:21 +00003250 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003251 return NULL;
3252}
3253
Alexander Belopolsky40018472011-02-26 01:02:56 +00003254PyObject *
3255PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003256 Py_ssize_t size,
3257 const char *encoding,
3258 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003259{
3260 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003261
Guido van Rossumd57fd912000-03-10 22:53:23 +00003262 unicode = PyUnicode_FromUnicode(s, size);
3263 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003264 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003265 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3266 Py_DECREF(unicode);
3267 return v;
3268}
3269
Alexander Belopolsky40018472011-02-26 01:02:56 +00003270PyObject *
3271PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003272 const char *encoding,
3273 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003274{
3275 PyObject *v;
3276
3277 if (!PyUnicode_Check(unicode)) {
3278 PyErr_BadArgument();
3279 goto onError;
3280 }
3281
3282 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003283 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003284
3285 /* Encode via the codec registry */
3286 v = PyCodec_Encode(unicode, encoding, errors);
3287 if (v == NULL)
3288 goto onError;
3289 return v;
3290
Benjamin Peterson29060642009-01-31 22:14:21 +00003291 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003292 return NULL;
3293}
3294
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003295static size_t
3296wcstombs_errorpos(const wchar_t *wstr)
3297{
3298 size_t len;
3299#if SIZEOF_WCHAR_T == 2
3300 wchar_t buf[3];
3301#else
3302 wchar_t buf[2];
3303#endif
3304 char outbuf[MB_LEN_MAX];
3305 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003307#if SIZEOF_WCHAR_T == 2
3308 buf[2] = 0;
3309#else
3310 buf[1] = 0;
3311#endif
3312 start = wstr;
3313 while (*wstr != L'\0')
3314 {
3315 previous = wstr;
3316#if SIZEOF_WCHAR_T == 2
3317 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3318 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3319 {
3320 buf[0] = wstr[0];
3321 buf[1] = wstr[1];
3322 wstr += 2;
3323 }
3324 else {
3325 buf[0] = *wstr;
3326 buf[1] = 0;
3327 wstr++;
3328 }
3329#else
3330 buf[0] = *wstr;
3331 wstr++;
3332#endif
3333 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003334 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003335 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003336 }
3337
3338 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003339 return 0;
3340}
3341
Victor Stinner1b579672011-12-17 05:47:23 +01003342static int
3343locale_error_handler(const char *errors, int *surrogateescape)
3344{
Victor Stinner50149202015-09-22 00:26:54 +02003345 _Py_error_handler error_handler = get_error_handler(errors);
3346 switch (error_handler)
3347 {
3348 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003349 *surrogateescape = 0;
3350 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003351 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003352 *surrogateescape = 1;
3353 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003354 default:
3355 PyErr_Format(PyExc_ValueError,
3356 "only 'strict' and 'surrogateescape' error handlers "
3357 "are supported, not '%s'",
3358 errors);
3359 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003360 }
Victor Stinner1b579672011-12-17 05:47:23 +01003361}
3362
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003363PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003364PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003365{
3366 Py_ssize_t wlen, wlen2;
3367 wchar_t *wstr;
3368 PyObject *bytes = NULL;
3369 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003370 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 PyObject *exc;
3372 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003373 int surrogateescape;
3374
3375 if (locale_error_handler(errors, &surrogateescape) < 0)
3376 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003377
3378 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3379 if (wstr == NULL)
3380 return NULL;
3381
3382 wlen2 = wcslen(wstr);
3383 if (wlen2 != wlen) {
3384 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003385 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003386 return NULL;
3387 }
3388
3389 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003390 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003391 char *str;
3392
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003393 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003394 if (str == NULL) {
3395 if (error_pos == (size_t)-1) {
3396 PyErr_NoMemory();
3397 PyMem_Free(wstr);
3398 return NULL;
3399 }
3400 else {
3401 goto encode_error;
3402 }
3403 }
3404 PyMem_Free(wstr);
3405
3406 bytes = PyBytes_FromString(str);
3407 PyMem_Free(str);
3408 }
3409 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003410 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003411 size_t len, len2;
3412
3413 len = wcstombs(NULL, wstr, 0);
3414 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003415 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003416 goto encode_error;
3417 }
3418
3419 bytes = PyBytes_FromStringAndSize(NULL, len);
3420 if (bytes == NULL) {
3421 PyMem_Free(wstr);
3422 return NULL;
3423 }
3424
3425 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3426 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003427 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003428 goto encode_error;
3429 }
3430 PyMem_Free(wstr);
3431 }
3432 return bytes;
3433
3434encode_error:
3435 errmsg = strerror(errno);
3436 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003437
3438 if (error_pos == (size_t)-1)
3439 error_pos = wcstombs_errorpos(wstr);
3440
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003441 PyMem_Free(wstr);
3442 Py_XDECREF(bytes);
3443
Victor Stinner2f197072011-12-17 07:08:30 +01003444 if (errmsg != NULL) {
3445 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003446 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003447 if (wstr != NULL) {
3448 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003449 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003450 } else
3451 errmsg = NULL;
3452 }
3453 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003454 reason = PyUnicode_FromString(
3455 "wcstombs() encountered an unencodable "
3456 "wide character");
3457 if (reason == NULL)
3458 return NULL;
3459
3460 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3461 "locale", unicode,
3462 (Py_ssize_t)error_pos,
3463 (Py_ssize_t)(error_pos+1),
3464 reason);
3465 Py_DECREF(reason);
3466 if (exc != NULL) {
3467 PyCodec_StrictErrors(exc);
3468 Py_XDECREF(exc);
3469 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003470 return NULL;
3471}
3472
Victor Stinnerad158722010-10-27 00:25:46 +00003473PyObject *
3474PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003475{
Victor Stinner99b95382011-07-04 14:23:54 +02003476#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003477 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003478#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003479 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003480#else
Victor Stinner793b5312011-04-27 00:24:21 +02003481 PyInterpreterState *interp = PyThreadState_GET()->interp;
3482 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3483 cannot use it to encode and decode filenames before it is loaded. Load
3484 the Python codec requires to encode at least its own filename. Use the C
3485 version of the locale codec until the codec registry is initialized and
3486 the Python codec is loaded.
3487
3488 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3489 cannot only rely on it: check also interp->fscodec_initialized for
3490 subinterpreters. */
3491 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003492 return PyUnicode_AsEncodedString(unicode,
3493 Py_FileSystemDefaultEncoding,
3494 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003495 }
3496 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003497 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003498 }
Victor Stinnerad158722010-10-27 00:25:46 +00003499#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003500}
3501
Alexander Belopolsky40018472011-02-26 01:02:56 +00003502PyObject *
3503PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003504 const char *encoding,
3505 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003506{
3507 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003508 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003509
Guido van Rossumd57fd912000-03-10 22:53:23 +00003510 if (!PyUnicode_Check(unicode)) {
3511 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003512 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003513 }
Fred Drakee4315f52000-05-09 19:53:39 +00003514
Fred Drakee4315f52000-05-09 19:53:39 +00003515 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003516 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003517 if ((strcmp(lower, "utf-8") == 0) ||
3518 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003519 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003520 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003521 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003522 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003523 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003524 }
Victor Stinner37296e82010-06-10 13:36:23 +00003525 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003526 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003527 (strcmp(lower, "iso-8859-1") == 0) ||
3528 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003529 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003530#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003531 else if (strcmp(lower, "mbcs") == 0)
3532 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003533#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003534 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003535 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003536 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003537
3538 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003539 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003540 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003541 return NULL;
3542
3543 /* The normal path */
3544 if (PyBytes_Check(v))
3545 return v;
3546
3547 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003548 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003549 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003550 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003551
3552 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003553 "encoder %s returned bytearray instead of bytes; "
3554 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003555 encoding);
3556 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003557 Py_DECREF(v);
3558 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003559 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003560
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003561 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3562 Py_DECREF(v);
3563 return b;
3564 }
3565
3566 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003567 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3568 "use codecs.encode() to encode to arbitrary types",
3569 encoding,
3570 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003571 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003572 return NULL;
3573}
3574
Alexander Belopolsky40018472011-02-26 01:02:56 +00003575PyObject *
3576PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003577 const char *encoding,
3578 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003579{
3580 PyObject *v;
3581
3582 if (!PyUnicode_Check(unicode)) {
3583 PyErr_BadArgument();
3584 goto onError;
3585 }
3586
3587 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003588 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003589
3590 /* Encode via the codec registry */
3591 v = PyCodec_Encode(unicode, encoding, errors);
3592 if (v == NULL)
3593 goto onError;
3594 if (!PyUnicode_Check(v)) {
3595 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003596 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3597 "use codecs.encode() to encode to arbitrary types",
3598 encoding,
3599 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003600 Py_DECREF(v);
3601 goto onError;
3602 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003603 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003604
Benjamin Peterson29060642009-01-31 22:14:21 +00003605 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003606 return NULL;
3607}
3608
Victor Stinner2f197072011-12-17 07:08:30 +01003609static size_t
3610mbstowcs_errorpos(const char *str, size_t len)
3611{
3612#ifdef HAVE_MBRTOWC
3613 const char *start = str;
3614 mbstate_t mbs;
3615 size_t converted;
3616 wchar_t ch;
3617
3618 memset(&mbs, 0, sizeof mbs);
3619 while (len)
3620 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003621 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003622 if (converted == 0)
3623 /* Reached end of string */
3624 break;
3625 if (converted == (size_t)-1 || converted == (size_t)-2) {
3626 /* Conversion error or incomplete character */
3627 return str - start;
3628 }
3629 else {
3630 str += converted;
3631 len -= converted;
3632 }
3633 }
3634 /* failed to find the undecodable byte sequence */
3635 return 0;
3636#endif
3637 return 0;
3638}
3639
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003640PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003641PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003642 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003643{
3644 wchar_t smallbuf[256];
3645 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3646 wchar_t *wstr;
3647 size_t wlen, wlen2;
3648 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003649 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003650 size_t error_pos;
3651 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003652 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3653 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003654
3655 if (locale_error_handler(errors, &surrogateescape) < 0)
3656 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003657
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003658 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3659 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003660 return NULL;
3661 }
3662
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003663 if (surrogateescape) {
3664 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003665 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003666 if (wstr == NULL) {
3667 if (wlen == (size_t)-1)
3668 PyErr_NoMemory();
3669 else
3670 PyErr_SetFromErrno(PyExc_OSError);
3671 return NULL;
3672 }
3673
3674 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003675 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003676 }
3677 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003678 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003679#ifndef HAVE_BROKEN_MBSTOWCS
3680 wlen = mbstowcs(NULL, str, 0);
3681#else
3682 wlen = len;
3683#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003684 if (wlen == (size_t)-1)
3685 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003686 if (wlen+1 <= smallbuf_len) {
3687 wstr = smallbuf;
3688 }
3689 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003690 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003691 if (!wstr)
3692 return PyErr_NoMemory();
3693 }
3694
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003695 wlen2 = mbstowcs(wstr, str, wlen+1);
3696 if (wlen2 == (size_t)-1) {
3697 if (wstr != smallbuf)
3698 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003699 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003700 }
3701#ifdef HAVE_BROKEN_MBSTOWCS
3702 assert(wlen2 == wlen);
3703#endif
3704 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3705 if (wstr != smallbuf)
3706 PyMem_Free(wstr);
3707 }
3708 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003709
3710decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003711 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003712 errmsg = strerror(errno);
3713 assert(errmsg != NULL);
3714
3715 error_pos = mbstowcs_errorpos(str, len);
3716 if (errmsg != NULL) {
3717 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003718 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003719 if (wstr != NULL) {
3720 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003721 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003722 }
Victor Stinner2f197072011-12-17 07:08:30 +01003723 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003724 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003725 reason = PyUnicode_FromString(
3726 "mbstowcs() encountered an invalid multibyte sequence");
3727 if (reason == NULL)
3728 return NULL;
3729
3730 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3731 "locale", str, len,
3732 (Py_ssize_t)error_pos,
3733 (Py_ssize_t)(error_pos+1),
3734 reason);
3735 Py_DECREF(reason);
3736 if (exc != NULL) {
3737 PyCodec_StrictErrors(exc);
3738 Py_XDECREF(exc);
3739 }
3740 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003741}
3742
3743PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003744PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003745{
3746 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003747 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003748}
3749
3750
3751PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003752PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003753 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003754 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3755}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003756
Christian Heimes5894ba72007-11-04 11:43:14 +00003757PyObject*
3758PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3759{
Victor Stinner99b95382011-07-04 14:23:54 +02003760#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003761 return PyUnicode_DecodeMBCS(s, size, NULL);
3762#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003763 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003764#else
Victor Stinner793b5312011-04-27 00:24:21 +02003765 PyInterpreterState *interp = PyThreadState_GET()->interp;
3766 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3767 cannot use it to encode and decode filenames before it is loaded. Load
3768 the Python codec requires to encode at least its own filename. Use the C
3769 version of the locale codec until the codec registry is initialized and
3770 the Python codec is loaded.
3771
3772 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3773 cannot only rely on it: check also interp->fscodec_initialized for
3774 subinterpreters. */
3775 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003776 return PyUnicode_Decode(s, size,
3777 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003778 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003779 }
3780 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003781 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003782 }
Victor Stinnerad158722010-10-27 00:25:46 +00003783#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003784}
3785
Martin v. Löwis011e8422009-05-05 04:43:17 +00003786
3787int
3788PyUnicode_FSConverter(PyObject* arg, void* addr)
3789{
3790 PyObject *output = NULL;
3791 Py_ssize_t size;
3792 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003793 if (arg == NULL) {
3794 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003795 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003796 return 1;
3797 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003798 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003799 output = arg;
3800 Py_INCREF(output);
3801 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003802 else if (PyUnicode_Check(arg)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003803 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003804 if (!output)
3805 return 0;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003806 assert(PyBytes_Check(output));
3807 }
3808 else {
3809 PyErr_Format(PyExc_TypeError,
3810 "must be str or bytes, not %.100s",
3811 Py_TYPE(arg)->tp_name);
3812 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003813 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003814 size = PyBytes_GET_SIZE(output);
3815 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003816 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003817 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003818 Py_DECREF(output);
3819 return 0;
3820 }
3821 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003822 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003823}
3824
3825
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003826int
3827PyUnicode_FSDecoder(PyObject* arg, void* addr)
3828{
3829 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003830 if (arg == NULL) {
3831 Py_DECREF(*(PyObject**)addr);
3832 return 1;
3833 }
3834 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003835 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003837 output = arg;
3838 Py_INCREF(output);
3839 }
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003840 else if (PyBytes_Check(arg) || PyObject_CheckBuffer(arg)) {
3841 if (!PyBytes_Check(arg) &&
3842 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3843 "path should be string or bytes, not %.200s",
3844 Py_TYPE(arg)->tp_name)) {
3845 return 0;
3846 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003847 arg = PyBytes_FromObject(arg);
3848 if (!arg)
3849 return 0;
3850 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3851 PyBytes_GET_SIZE(arg));
3852 Py_DECREF(arg);
3853 if (!output)
3854 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003855 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003856 else {
3857 PyErr_Format(PyExc_TypeError,
3858 "path should be string or bytes, not %.200s",
3859 Py_TYPE(arg)->tp_name);
3860 return 0;
3861 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003862 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003863 Py_DECREF(output);
3864 return 0;
3865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003867 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003868 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003869 Py_DECREF(output);
3870 return 0;
3871 }
3872 *(PyObject**)addr = output;
3873 return Py_CLEANUP_SUPPORTED;
3874}
3875
3876
Martin v. Löwis5b222132007-06-10 09:51:05 +00003877char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003879{
Christian Heimesf3863112007-11-22 07:46:41 +00003880 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003882 if (!PyUnicode_Check(unicode)) {
3883 PyErr_BadArgument();
3884 return NULL;
3885 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003886 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003887 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003888
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003889 if (PyUnicode_UTF8(unicode) == NULL) {
3890 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003891 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892 if (bytes == NULL)
3893 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003894 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3895 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003896 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003897 Py_DECREF(bytes);
3898 return NULL;
3899 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003900 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3901 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3902 PyBytes_AS_STRING(bytes),
3903 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904 Py_DECREF(bytes);
3905 }
3906
3907 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003908 *psize = PyUnicode_UTF8_LENGTH(unicode);
3909 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003910}
3911
3912char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003914{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003915 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3916}
3917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003918Py_UNICODE *
3919PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3920{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003921 const unsigned char *one_byte;
3922#if SIZEOF_WCHAR_T == 4
3923 const Py_UCS2 *two_bytes;
3924#else
3925 const Py_UCS4 *four_bytes;
3926 const Py_UCS4 *ucs4_end;
3927 Py_ssize_t num_surrogates;
3928#endif
3929 wchar_t *w;
3930 wchar_t *wchar_end;
3931
3932 if (!PyUnicode_Check(unicode)) {
3933 PyErr_BadArgument();
3934 return NULL;
3935 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003936 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003938 assert(_PyUnicode_KIND(unicode) != 0);
3939 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003942#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003943 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3944 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945 num_surrogates = 0;
3946
3947 for (; four_bytes < ucs4_end; ++four_bytes) {
3948 if (*four_bytes > 0xFFFF)
3949 ++num_surrogates;
3950 }
3951
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003952 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3953 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3954 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955 PyErr_NoMemory();
3956 return NULL;
3957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003958 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003960 w = _PyUnicode_WSTR(unicode);
3961 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3962 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003963 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3964 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003965 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003966 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003967 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3968 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969 }
3970 else
3971 *w = *four_bytes;
3972
3973 if (w > wchar_end) {
3974 assert(0 && "Miscalculated string end");
3975 }
3976 }
3977 *w = 0;
3978#else
3979 /* sizeof(wchar_t) == 4 */
3980 Py_FatalError("Impossible unicode object state, wstr and str "
3981 "should share memory already.");
3982 return NULL;
3983#endif
3984 }
3985 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003986 if ((size_t)_PyUnicode_LENGTH(unicode) >
3987 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3988 PyErr_NoMemory();
3989 return NULL;
3990 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003991 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3992 (_PyUnicode_LENGTH(unicode) + 1));
3993 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003994 PyErr_NoMemory();
3995 return NULL;
3996 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003997 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3998 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3999 w = _PyUnicode_WSTR(unicode);
4000 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004002 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4003 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004 for (; w < wchar_end; ++one_byte, ++w)
4005 *w = *one_byte;
4006 /* null-terminate the wstr */
4007 *w = 0;
4008 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004009 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004010#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004011 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004012 for (; w < wchar_end; ++two_bytes, ++w)
4013 *w = *two_bytes;
4014 /* null-terminate the wstr */
4015 *w = 0;
4016#else
4017 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004018 PyObject_FREE(_PyUnicode_WSTR(unicode));
4019 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004020 Py_FatalError("Impossible unicode object state, wstr "
4021 "and str should share memory already.");
4022 return NULL;
4023#endif
4024 }
4025 else {
4026 assert(0 && "This should never happen.");
4027 }
4028 }
4029 }
4030 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004031 *size = PyUnicode_WSTR_LENGTH(unicode);
4032 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004033}
4034
Alexander Belopolsky40018472011-02-26 01:02:56 +00004035Py_UNICODE *
4036PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004037{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004039}
4040
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041
Alexander Belopolsky40018472011-02-26 01:02:56 +00004042Py_ssize_t
4043PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004044{
4045 if (!PyUnicode_Check(unicode)) {
4046 PyErr_BadArgument();
4047 goto onError;
4048 }
4049 return PyUnicode_GET_SIZE(unicode);
4050
Benjamin Peterson29060642009-01-31 22:14:21 +00004051 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004052 return -1;
4053}
4054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004055Py_ssize_t
4056PyUnicode_GetLength(PyObject *unicode)
4057{
Victor Stinner07621332012-06-16 04:53:46 +02004058 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004059 PyErr_BadArgument();
4060 return -1;
4061 }
Victor Stinner07621332012-06-16 04:53:46 +02004062 if (PyUnicode_READY(unicode) == -1)
4063 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004064 return PyUnicode_GET_LENGTH(unicode);
4065}
4066
4067Py_UCS4
4068PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4069{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004070 void *data;
4071 int kind;
4072
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004073 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4074 PyErr_BadArgument();
4075 return (Py_UCS4)-1;
4076 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004077 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004078 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004079 return (Py_UCS4)-1;
4080 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004081 data = PyUnicode_DATA(unicode);
4082 kind = PyUnicode_KIND(unicode);
4083 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004084}
4085
4086int
4087PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4088{
4089 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004090 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004091 return -1;
4092 }
Victor Stinner488fa492011-12-12 00:01:39 +01004093 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004094 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004095 PyErr_SetString(PyExc_IndexError, "string index out of range");
4096 return -1;
4097 }
Victor Stinner488fa492011-12-12 00:01:39 +01004098 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004099 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004100 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4101 PyErr_SetString(PyExc_ValueError, "character out of range");
4102 return -1;
4103 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004104 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4105 index, ch);
4106 return 0;
4107}
4108
Alexander Belopolsky40018472011-02-26 01:02:56 +00004109const char *
4110PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004111{
Victor Stinner42cb4622010-09-01 19:39:01 +00004112 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004113}
4114
Victor Stinner554f3f02010-06-16 23:33:54 +00004115/* create or adjust a UnicodeDecodeError */
4116static void
4117make_decode_exception(PyObject **exceptionObject,
4118 const char *encoding,
4119 const char *input, Py_ssize_t length,
4120 Py_ssize_t startpos, Py_ssize_t endpos,
4121 const char *reason)
4122{
4123 if (*exceptionObject == NULL) {
4124 *exceptionObject = PyUnicodeDecodeError_Create(
4125 encoding, input, length, startpos, endpos, reason);
4126 }
4127 else {
4128 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4129 goto onError;
4130 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4131 goto onError;
4132 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4133 goto onError;
4134 }
4135 return;
4136
4137onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004138 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004139}
4140
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004141#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004142/* error handling callback helper:
4143 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004144 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004145 and adjust various state variables.
4146 return 0 on success, -1 on error
4147*/
4148
Alexander Belopolsky40018472011-02-26 01:02:56 +00004149static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004150unicode_decode_call_errorhandler_wchar(
4151 const char *errors, PyObject **errorHandler,
4152 const char *encoding, const char *reason,
4153 const char **input, const char **inend, Py_ssize_t *startinpos,
4154 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4155 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004156{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004157 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004158
4159 PyObject *restuple = NULL;
4160 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004161 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004162 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004163 Py_ssize_t requiredsize;
4164 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004165 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004166 wchar_t *repwstr;
4167 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004168
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004169 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4170 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004171
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004173 *errorHandler = PyCodec_LookupError(errors);
4174 if (*errorHandler == NULL)
4175 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004176 }
4177
Victor Stinner554f3f02010-06-16 23:33:54 +00004178 make_decode_exception(exceptionObject,
4179 encoding,
4180 *input, *inend - *input,
4181 *startinpos, *endinpos,
4182 reason);
4183 if (*exceptionObject == NULL)
4184 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004185
4186 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4187 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004189 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004190 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004191 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004192 }
4193 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004194 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004195
4196 /* Copy back the bytes variables, which might have been modified by the
4197 callback */
4198 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4199 if (!inputobj)
4200 goto onError;
4201 if (!PyBytes_Check(inputobj)) {
4202 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4203 }
4204 *input = PyBytes_AS_STRING(inputobj);
4205 insize = PyBytes_GET_SIZE(inputobj);
4206 *inend = *input + insize;
4207 /* we can DECREF safely, as the exception has another reference,
4208 so the object won't go away. */
4209 Py_DECREF(inputobj);
4210
4211 if (newpos<0)
4212 newpos = insize+newpos;
4213 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004214 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004215 goto onError;
4216 }
4217
4218 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4219 if (repwstr == NULL)
4220 goto onError;
4221 /* need more space? (at least enough for what we
4222 have+the replacement+the rest of the string (starting
4223 at the new input position), so we won't have to check space
4224 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004225 requiredsize = *outpos;
4226 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4227 goto overflow;
4228 requiredsize += repwlen;
4229 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4230 goto overflow;
4231 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004232 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004233 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004234 requiredsize = 2*outsize;
4235 if (unicode_resize(output, requiredsize) < 0)
4236 goto onError;
4237 }
4238 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4239 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004240 *endinpos = newpos;
4241 *inptr = *input + newpos;
4242
4243 /* we made it! */
4244 Py_XDECREF(restuple);
4245 return 0;
4246
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004247 overflow:
4248 PyErr_SetString(PyExc_OverflowError,
4249 "decoded result is too long for a Python string");
4250
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004251 onError:
4252 Py_XDECREF(restuple);
4253 return -1;
4254}
4255#endif /* HAVE_MBCS */
4256
4257static int
4258unicode_decode_call_errorhandler_writer(
4259 const char *errors, PyObject **errorHandler,
4260 const char *encoding, const char *reason,
4261 const char **input, const char **inend, Py_ssize_t *startinpos,
4262 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4263 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4264{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004265 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004266
4267 PyObject *restuple = NULL;
4268 PyObject *repunicode = NULL;
4269 Py_ssize_t insize;
4270 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004271 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004272 PyObject *inputobj = NULL;
4273
4274 if (*errorHandler == NULL) {
4275 *errorHandler = PyCodec_LookupError(errors);
4276 if (*errorHandler == NULL)
4277 goto onError;
4278 }
4279
4280 make_decode_exception(exceptionObject,
4281 encoding,
4282 *input, *inend - *input,
4283 *startinpos, *endinpos,
4284 reason);
4285 if (*exceptionObject == NULL)
4286 goto onError;
4287
4288 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4289 if (restuple == NULL)
4290 goto onError;
4291 if (!PyTuple_Check(restuple)) {
4292 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4293 goto onError;
4294 }
4295 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004296 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004297
4298 /* Copy back the bytes variables, which might have been modified by the
4299 callback */
4300 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4301 if (!inputobj)
4302 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004303 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004304 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004305 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004306 *input = PyBytes_AS_STRING(inputobj);
4307 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004308 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004309 /* we can DECREF safely, as the exception has another reference,
4310 so the object won't go away. */
4311 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004312
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004313 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004314 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004315 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004316 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004317 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004318 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319
Victor Stinner8f674cc2013-04-17 23:02:17 +02004320 if (PyUnicode_READY(repunicode) < 0)
4321 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004322 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004323 if (replen > 1) {
4324 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004325 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004326 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4327 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4328 goto onError;
4329 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004330 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004331 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004332
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004333 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004334 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004335
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004336 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004337 Py_XDECREF(restuple);
4338 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004339
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004341 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004342 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004343}
4344
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345/* --- UTF-7 Codec -------------------------------------------------------- */
4346
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347/* See RFC2152 for details. We encode conservatively and decode liberally. */
4348
4349/* Three simple macros defining base-64. */
4350
4351/* Is c a base-64 character? */
4352
4353#define IS_BASE64(c) \
4354 (((c) >= 'A' && (c) <= 'Z') || \
4355 ((c) >= 'a' && (c) <= 'z') || \
4356 ((c) >= '0' && (c) <= '9') || \
4357 (c) == '+' || (c) == '/')
4358
4359/* given that c is a base-64 character, what is its base-64 value? */
4360
4361#define FROM_BASE64(c) \
4362 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4363 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4364 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4365 (c) == '+' ? 62 : 63)
4366
4367/* What is the base-64 character of the bottom 6 bits of n? */
4368
4369#define TO_BASE64(n) \
4370 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4371
4372/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4373 * decoded as itself. We are permissive on decoding; the only ASCII
4374 * byte not decoding to itself is the + which begins a base64
4375 * string. */
4376
4377#define DECODE_DIRECT(c) \
4378 ((c) <= 127 && (c) != '+')
4379
4380/* The UTF-7 encoder treats ASCII characters differently according to
4381 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4382 * the above). See RFC2152. This array identifies these different
4383 * sets:
4384 * 0 : "Set D"
4385 * alphanumeric and '(),-./:?
4386 * 1 : "Set O"
4387 * !"#$%&*;<=>@[]^_`{|}
4388 * 2 : "whitespace"
4389 * ht nl cr sp
4390 * 3 : special (must be base64 encoded)
4391 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4392 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004393
Tim Petersced69f82003-09-16 20:30:58 +00004394static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395char utf7_category[128] = {
4396/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4397 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4398/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4399 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4400/* sp ! " # $ % & ' ( ) * + , - . / */
4401 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4402/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4403 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4404/* @ A B C D E F G H I J K L M N O */
4405 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4406/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4407 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4408/* ` a b c d e f g h i j k l m n o */
4409 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4410/* p q r s t u v w x y z { | } ~ del */
4411 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412};
4413
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414/* ENCODE_DIRECT: this character should be encoded as itself. The
4415 * answer depends on whether we are encoding set O as itself, and also
4416 * on whether we are encoding whitespace as itself. RFC2152 makes it
4417 * clear that the answers to these questions vary between
4418 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004419
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420#define ENCODE_DIRECT(c, directO, directWS) \
4421 ((c) < 128 && (c) > 0 && \
4422 ((utf7_category[(c)] == 0) || \
4423 (directWS && (utf7_category[(c)] == 2)) || \
4424 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425
Alexander Belopolsky40018472011-02-26 01:02:56 +00004426PyObject *
4427PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004428 Py_ssize_t size,
4429 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004431 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4432}
4433
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434/* The decoder. The only state we preserve is our read position,
4435 * i.e. how many characters we have consumed. So if we end in the
4436 * middle of a shift sequence we have to back off the read position
4437 * and the output to the beginning of the sequence, otherwise we lose
4438 * all the shift state (seen bits, number of bits seen, high
4439 * surrogate). */
4440
Alexander Belopolsky40018472011-02-26 01:02:56 +00004441PyObject *
4442PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004443 Py_ssize_t size,
4444 const char *errors,
4445 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004446{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004447 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004448 Py_ssize_t startinpos;
4449 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004451 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 const char *errmsg = "";
4453 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004454 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 unsigned int base64bits = 0;
4456 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004457 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004458 PyObject *errorHandler = NULL;
4459 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004460
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004461 if (size == 0) {
4462 if (consumed)
4463 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004464 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004465 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004467 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004468 _PyUnicodeWriter_Init(&writer);
4469 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470
4471 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 e = s + size;
4473
4474 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004475 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004476 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004477 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 if (inShift) { /* in a base-64 section */
4480 if (IS_BASE64(ch)) { /* consume a base-64 character */
4481 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4482 base64bits += 6;
4483 s++;
4484 if (base64bits >= 16) {
4485 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004486 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 base64bits -= 16;
4488 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004489 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 if (surrogate) {
4491 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004492 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4493 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004494 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004495 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004496 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004497 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 }
4499 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004500 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004501 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004503 }
4504 }
Victor Stinner551ac952011-11-29 22:58:13 +01004505 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506 /* first surrogate */
4507 surrogate = outCh;
4508 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004510 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004511 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 }
4513 }
4514 }
4515 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004516 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 if (base64bits > 0) { /* left-over bits */
4518 if (base64bits >= 6) {
4519 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004520 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521 errmsg = "partial character in shift sequence";
4522 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004523 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004524 else {
4525 /* Some bits remain; they should be zero */
4526 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004527 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004528 errmsg = "non-zero padding bits in shift sequence";
4529 goto utf7Error;
4530 }
4531 }
4532 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004533 if (surrogate && DECODE_DIRECT(ch)) {
4534 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4535 goto onError;
4536 }
4537 surrogate = 0;
4538 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 /* '-' is absorbed; other terminating
4540 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004541 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004543 }
4544 }
4545 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004546 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 s++; /* consume '+' */
4548 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004549 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004550 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004551 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552 }
4553 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004555 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004556 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004557 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004558 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559 }
4560 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004563 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004564 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004565 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 else {
4567 startinpos = s-starts;
4568 s++;
4569 errmsg = "unexpected special character";
4570 goto utf7Error;
4571 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004574 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004575 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004576 errors, &errorHandler,
4577 "utf7", errmsg,
4578 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004579 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004580 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004581 }
4582
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 /* end of string */
4584
4585 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4586 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004587 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 if (surrogate ||
4589 (base64bits >= 6) ||
4590 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004591 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004592 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 errors, &errorHandler,
4594 "utf7", "unterminated shift sequence",
4595 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004596 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004597 goto onError;
4598 if (s < e)
4599 goto restart;
4600 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004601 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602
4603 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004604 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004606 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004607 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004608 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004609 writer.kind, writer.data, shiftOutStart);
4610 Py_XDECREF(errorHandler);
4611 Py_XDECREF(exc);
4612 _PyUnicodeWriter_Dealloc(&writer);
4613 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004614 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004615 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004616 }
4617 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004618 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004620 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004622 Py_XDECREF(errorHandler);
4623 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004624 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004625
Benjamin Peterson29060642009-01-31 22:14:21 +00004626 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004627 Py_XDECREF(errorHandler);
4628 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004629 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004630 return NULL;
4631}
4632
4633
Alexander Belopolsky40018472011-02-26 01:02:56 +00004634PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004635_PyUnicode_EncodeUTF7(PyObject *str,
4636 int base64SetO,
4637 int base64WhiteSpace,
4638 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004639{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004640 int kind;
4641 void *data;
4642 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004643 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004644 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004645 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 unsigned int base64bits = 0;
4647 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004648 char * out;
4649 char * start;
4650
Benjamin Petersonbac79492012-01-14 13:34:47 -05004651 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004652 return NULL;
4653 kind = PyUnicode_KIND(str);
4654 data = PyUnicode_DATA(str);
4655 len = PyUnicode_GET_LENGTH(str);
4656
4657 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004658 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004660 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004661 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004662 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004663 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004664 if (v == NULL)
4665 return NULL;
4666
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004667 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004668 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004669 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004670
Antoine Pitrou244651a2009-05-04 18:56:13 +00004671 if (inShift) {
4672 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4673 /* shifting out */
4674 if (base64bits) { /* output remaining bits */
4675 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4676 base64buffer = 0;
4677 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004678 }
4679 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004680 /* Characters not in the BASE64 set implicitly unshift the sequence
4681 so no '-' is required, except if the character is itself a '-' */
4682 if (IS_BASE64(ch) || ch == '-') {
4683 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004684 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685 *out++ = (char) ch;
4686 }
4687 else {
4688 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004689 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004690 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004691 else { /* not in a shift sequence */
4692 if (ch == '+') {
4693 *out++ = '+';
4694 *out++ = '-';
4695 }
4696 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4697 *out++ = (char) ch;
4698 }
4699 else {
4700 *out++ = '+';
4701 inShift = 1;
4702 goto encode_char;
4703 }
4704 }
4705 continue;
4706encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004707 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004708 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004709
Antoine Pitrou244651a2009-05-04 18:56:13 +00004710 /* code first surrogate */
4711 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004712 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004713 while (base64bits >= 6) {
4714 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4715 base64bits -= 6;
4716 }
4717 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004718 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004719 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004720 base64bits += 16;
4721 base64buffer = (base64buffer << 16) | ch;
4722 while (base64bits >= 6) {
4723 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4724 base64bits -= 6;
4725 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004726 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004727 if (base64bits)
4728 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4729 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004730 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004731 if (_PyBytes_Resize(&v, out - start) < 0)
4732 return NULL;
4733 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004735PyObject *
4736PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4737 Py_ssize_t size,
4738 int base64SetO,
4739 int base64WhiteSpace,
4740 const char *errors)
4741{
4742 PyObject *result;
4743 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4744 if (tmp == NULL)
4745 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004746 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004747 base64WhiteSpace, errors);
4748 Py_DECREF(tmp);
4749 return result;
4750}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004751
Antoine Pitrou244651a2009-05-04 18:56:13 +00004752#undef IS_BASE64
4753#undef FROM_BASE64
4754#undef TO_BASE64
4755#undef DECODE_DIRECT
4756#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004757
Guido van Rossumd57fd912000-03-10 22:53:23 +00004758/* --- UTF-8 Codec -------------------------------------------------------- */
4759
Alexander Belopolsky40018472011-02-26 01:02:56 +00004760PyObject *
4761PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004762 Py_ssize_t size,
4763 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764{
Walter Dörwald69652032004-09-07 20:24:22 +00004765 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4766}
4767
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768#include "stringlib/asciilib.h"
4769#include "stringlib/codecs.h"
4770#include "stringlib/undef.h"
4771
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004772#include "stringlib/ucs1lib.h"
4773#include "stringlib/codecs.h"
4774#include "stringlib/undef.h"
4775
4776#include "stringlib/ucs2lib.h"
4777#include "stringlib/codecs.h"
4778#include "stringlib/undef.h"
4779
4780#include "stringlib/ucs4lib.h"
4781#include "stringlib/codecs.h"
4782#include "stringlib/undef.h"
4783
Antoine Pitrouab868312009-01-10 15:40:25 +00004784/* Mask to quickly check whether a C 'long' contains a
4785 non-ASCII, UTF8-encoded char. */
4786#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004787# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004788#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004789# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004790#else
4791# error C 'long' size should be either 4 or 8!
4792#endif
4793
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004794static Py_ssize_t
4795ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004796{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004797 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004798 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004799
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004800 /*
4801 * Issue #17237: m68k is a bit different from most architectures in
4802 * that objects do not use "natural alignment" - for example, int and
4803 * long are only aligned at 2-byte boundaries. Therefore the assert()
4804 * won't work; also, tests have shown that skipping the "optimised
4805 * version" will even speed up m68k.
4806 */
4807#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004808#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004809 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4810 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 /* Fast path, see in STRINGLIB(utf8_decode) for
4812 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004813 /* Help allocation */
4814 const char *_p = p;
4815 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004816 while (_p < aligned_end) {
4817 unsigned long value = *(const unsigned long *) _p;
4818 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004819 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004820 *((unsigned long *)q) = value;
4821 _p += SIZEOF_LONG;
4822 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004823 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004824 p = _p;
4825 while (p < end) {
4826 if ((unsigned char)*p & 0x80)
4827 break;
4828 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004829 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004830 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004831 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004832#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004833#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004834 while (p < end) {
4835 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4836 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004837 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004838 /* Help allocation */
4839 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004840 while (_p < aligned_end) {
4841 unsigned long value = *(unsigned long *) _p;
4842 if (value & ASCII_CHAR_MASK)
4843 break;
4844 _p += SIZEOF_LONG;
4845 }
4846 p = _p;
4847 if (_p == end)
4848 break;
4849 }
4850 if ((unsigned char)*p & 0x80)
4851 break;
4852 ++p;
4853 }
4854 memcpy(dest, start, p - start);
4855 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004856}
Antoine Pitrouab868312009-01-10 15:40:25 +00004857
Victor Stinner785938e2011-12-11 20:09:03 +01004858PyObject *
4859PyUnicode_DecodeUTF8Stateful(const char *s,
4860 Py_ssize_t size,
4861 const char *errors,
4862 Py_ssize_t *consumed)
4863{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004864 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004865 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867
4868 Py_ssize_t startinpos;
4869 Py_ssize_t endinpos;
4870 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004871 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004873 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004874
4875 if (size == 0) {
4876 if (consumed)
4877 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004878 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004879 }
4880
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004881 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4882 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004883 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884 *consumed = 1;
4885 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004886 }
4887
Victor Stinner8f674cc2013-04-17 23:02:17 +02004888 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004889 writer.min_length = size;
4890 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004891 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004892
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004893 writer.pos = ascii_decode(s, end, writer.data);
4894 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004895 while (s < end) {
4896 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004897 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004898
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004899 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004900 if (PyUnicode_IS_ASCII(writer.buffer))
4901 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004902 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004903 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004904 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004905 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004906 } else {
4907 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004908 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004909 }
4910
4911 switch (ch) {
4912 case 0:
4913 if (s == end || consumed)
4914 goto End;
4915 errmsg = "unexpected end of data";
4916 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004917 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 break;
4919 case 1:
4920 errmsg = "invalid start byte";
4921 startinpos = s - starts;
4922 endinpos = startinpos + 1;
4923 break;
4924 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004925 case 3:
4926 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004927 errmsg = "invalid continuation byte";
4928 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004929 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004930 break;
4931 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004932 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004933 goto onError;
4934 continue;
4935 }
4936
Victor Stinner1d65d912015-10-05 13:43:50 +02004937 if (error_handler == _Py_ERROR_UNKNOWN)
4938 error_handler = get_error_handler(errors);
4939
4940 switch (error_handler) {
4941 case _Py_ERROR_IGNORE:
4942 s += (endinpos - startinpos);
4943 break;
4944
4945 case _Py_ERROR_REPLACE:
4946 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4947 goto onError;
4948 s += (endinpos - startinpos);
4949 break;
4950
4951 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004952 {
4953 Py_ssize_t i;
4954
Victor Stinner1d65d912015-10-05 13:43:50 +02004955 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4956 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004957 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004958 ch = (Py_UCS4)(unsigned char)(starts[i]);
4959 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4960 ch + 0xdc00);
4961 writer.pos++;
4962 }
4963 s += (endinpos - startinpos);
4964 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004965 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004966
4967 default:
4968 if (unicode_decode_call_errorhandler_writer(
4969 errors, &error_handler_obj,
4970 "utf-8", errmsg,
4971 &starts, &end, &startinpos, &endinpos, &exc, &s,
4972 &writer))
4973 goto onError;
4974 }
Victor Stinner785938e2011-12-11 20:09:03 +01004975 }
4976
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004978 if (consumed)
4979 *consumed = s - starts;
4980
Victor Stinner1d65d912015-10-05 13:43:50 +02004981 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004982 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004984
4985onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004986 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004988 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004990}
4991
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004992#ifdef __APPLE__
4993
4994/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004995 used to decode the command line arguments on Mac OS X.
4996
4997 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004998 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004999
5000wchar_t*
5001_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5002{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005003 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 wchar_t *unicode;
5005 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005006
5007 /* Note: size will always be longer than the resulting Unicode
5008 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005009 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005010 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005011 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005012 if (!unicode)
5013 return NULL;
5014
5015 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005016 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005018 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005019 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005020#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005021 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005022#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005024#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005025 if (ch > 0xFF) {
5026#if SIZEOF_WCHAR_T == 4
5027 assert(0);
5028#else
5029 assert(Py_UNICODE_IS_SURROGATE(ch));
5030 /* compute and append the two surrogates: */
5031 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5032 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5033#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005034 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005035 else {
5036 if (!ch && s == e)
5037 break;
5038 /* surrogateescape */
5039 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5040 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005041 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005042 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005043 return unicode;
5044}
5045
5046#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005048/* Primary internal function which creates utf8 encoded bytes objects.
5049
5050 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005051 and allocate exactly as much space needed at the end. Else allocate the
5052 maximum possible needed (4 result bytes per Unicode character), and return
5053 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005054*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005055PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005056_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005057{
Victor Stinner6099a032011-12-18 14:22:26 +01005058 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005059 void *data;
5060 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005062 if (!PyUnicode_Check(unicode)) {
5063 PyErr_BadArgument();
5064 return NULL;
5065 }
5066
5067 if (PyUnicode_READY(unicode) == -1)
5068 return NULL;
5069
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005070 if (PyUnicode_UTF8(unicode))
5071 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5072 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005073
5074 kind = PyUnicode_KIND(unicode);
5075 data = PyUnicode_DATA(unicode);
5076 size = PyUnicode_GET_LENGTH(unicode);
5077
Benjamin Petersonead6b532011-12-20 17:23:42 -06005078 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005079 default:
5080 assert(0);
5081 case PyUnicode_1BYTE_KIND:
5082 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5083 assert(!PyUnicode_IS_ASCII(unicode));
5084 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5085 case PyUnicode_2BYTE_KIND:
5086 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5087 case PyUnicode_4BYTE_KIND:
5088 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005089 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005090}
5091
Alexander Belopolsky40018472011-02-26 01:02:56 +00005092PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005093PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5094 Py_ssize_t size,
5095 const char *errors)
5096{
5097 PyObject *v, *unicode;
5098
5099 unicode = PyUnicode_FromUnicode(s, size);
5100 if (unicode == NULL)
5101 return NULL;
5102 v = _PyUnicode_AsUTF8String(unicode, errors);
5103 Py_DECREF(unicode);
5104 return v;
5105}
5106
5107PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005108PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005109{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005110 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005111}
5112
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113/* --- UTF-32 Codec ------------------------------------------------------- */
5114
5115PyObject *
5116PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 Py_ssize_t size,
5118 const char *errors,
5119 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005120{
5121 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5122}
5123
5124PyObject *
5125PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005126 Py_ssize_t size,
5127 const char *errors,
5128 int *byteorder,
5129 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005130{
5131 const char *starts = s;
5132 Py_ssize_t startinpos;
5133 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005134 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005135 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005136 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005137 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139 PyObject *errorHandler = NULL;
5140 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005141
Walter Dörwald41980ca2007-08-16 21:55:45 +00005142 q = (unsigned char *)s;
5143 e = q + size;
5144
5145 if (byteorder)
5146 bo = *byteorder;
5147
5148 /* Check for BOM marks (U+FEFF) in the input and adjust current
5149 byte order setting accordingly. In native mode, the leading BOM
5150 mark is skipped, in all other modes, it is copied to the output
5151 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005152 if (bo == 0 && size >= 4) {
5153 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5154 if (bom == 0x0000FEFF) {
5155 bo = -1;
5156 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005157 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005158 else if (bom == 0xFFFE0000) {
5159 bo = 1;
5160 q += 4;
5161 }
5162 if (byteorder)
5163 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005164 }
5165
Victor Stinnere64322e2012-10-30 23:12:47 +01005166 if (q == e) {
5167 if (consumed)
5168 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005169 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005170 }
5171
Victor Stinnere64322e2012-10-30 23:12:47 +01005172#ifdef WORDS_BIGENDIAN
5173 le = bo < 0;
5174#else
5175 le = bo <= 0;
5176#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005177 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005178
Victor Stinner8f674cc2013-04-17 23:02:17 +02005179 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005180 writer.min_length = (e - q + 3) / 4;
5181 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005182 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005183
Victor Stinnere64322e2012-10-30 23:12:47 +01005184 while (1) {
5185 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005186 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005187
Victor Stinnere64322e2012-10-30 23:12:47 +01005188 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005189 enum PyUnicode_Kind kind = writer.kind;
5190 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005191 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005192 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005193 if (le) {
5194 do {
5195 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5196 if (ch > maxch)
5197 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005198 if (kind != PyUnicode_1BYTE_KIND &&
5199 Py_UNICODE_IS_SURROGATE(ch))
5200 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005201 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005202 q += 4;
5203 } while (q <= last);
5204 }
5205 else {
5206 do {
5207 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5208 if (ch > maxch)
5209 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005210 if (kind != PyUnicode_1BYTE_KIND &&
5211 Py_UNICODE_IS_SURROGATE(ch))
5212 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005213 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005214 q += 4;
5215 } while (q <= last);
5216 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005217 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005218 }
5219
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005220 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005221 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005222 startinpos = ((const char *)q) - starts;
5223 endinpos = startinpos + 4;
5224 }
5225 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005226 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005227 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005228 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005229 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005230 startinpos = ((const char *)q) - starts;
5231 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005233 else {
5234 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005235 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005236 goto onError;
5237 q += 4;
5238 continue;
5239 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005240 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005241 startinpos = ((const char *)q) - starts;
5242 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005244
5245 /* The remaining input chars are ignored if the callback
5246 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005247 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005249 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005250 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005251 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005252 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005253 }
5254
Walter Dörwald41980ca2007-08-16 21:55:45 +00005255 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005256 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258 Py_XDECREF(errorHandler);
5259 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005260 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005261
Benjamin Peterson29060642009-01-31 22:14:21 +00005262 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005263 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264 Py_XDECREF(errorHandler);
5265 Py_XDECREF(exc);
5266 return NULL;
5267}
5268
5269PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005270_PyUnicode_EncodeUTF32(PyObject *str,
5271 const char *errors,
5272 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005273{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005274 enum PyUnicode_Kind kind;
5275 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005276 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005277 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005278 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005279#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005280 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005281#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005282 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005283#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005284 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005285 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005286 PyObject *errorHandler = NULL;
5287 PyObject *exc = NULL;
5288 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005289
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005290 if (!PyUnicode_Check(str)) {
5291 PyErr_BadArgument();
5292 return NULL;
5293 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005294 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005295 return NULL;
5296 kind = PyUnicode_KIND(str);
5297 data = PyUnicode_DATA(str);
5298 len = PyUnicode_GET_LENGTH(str);
5299
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005300 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005301 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005302 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005303 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005304 if (v == NULL)
5305 return NULL;
5306
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005307 /* output buffer is 4-bytes aligned */
5308 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5309 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005310 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005311 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005312 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005313 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005314
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005315 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005316 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005317 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005318 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005319 else
5320 encoding = "utf-32";
5321
5322 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005323 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5324 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005325 }
5326
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005327 pos = 0;
5328 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005329 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005330
5331 if (kind == PyUnicode_2BYTE_KIND) {
5332 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5333 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005334 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005335 else {
5336 assert(kind == PyUnicode_4BYTE_KIND);
5337 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5338 &out, native_ordering);
5339 }
5340 if (pos == len)
5341 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005342
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005343 rep = unicode_encode_call_errorhandler(
5344 errors, &errorHandler,
5345 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005346 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005347 if (!rep)
5348 goto error;
5349
5350 if (PyBytes_Check(rep)) {
5351 repsize = PyBytes_GET_SIZE(rep);
5352 if (repsize & 3) {
5353 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005354 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005355 "surrogates not allowed");
5356 goto error;
5357 }
5358 moreunits = repsize / 4;
5359 }
5360 else {
5361 assert(PyUnicode_Check(rep));
5362 if (PyUnicode_READY(rep) < 0)
5363 goto error;
5364 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5365 if (!PyUnicode_IS_ASCII(rep)) {
5366 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 "surrogates not allowed");
5369 goto error;
5370 }
5371 }
5372
5373 /* four bytes are reserved for each surrogate */
5374 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005375 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005376 Py_ssize_t morebytes = 4 * (moreunits - 1);
5377 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5378 /* integer overflow */
5379 PyErr_NoMemory();
5380 goto error;
5381 }
5382 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5383 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005384 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005385 }
5386
5387 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005388 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5389 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005390 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005391 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005392 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5393 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005394 }
5395
5396 Py_CLEAR(rep);
5397 }
5398
5399 /* Cut back to size actually needed. This is necessary for, for example,
5400 encoding of a string containing isolated surrogates and the 'ignore'
5401 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 if (nsize != PyBytes_GET_SIZE(v))
5404 _PyBytes_Resize(&v, nsize);
5405 Py_XDECREF(errorHandler);
5406 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005407 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005408 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005409 error:
5410 Py_XDECREF(rep);
5411 Py_XDECREF(errorHandler);
5412 Py_XDECREF(exc);
5413 Py_XDECREF(v);
5414 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005415}
5416
Alexander Belopolsky40018472011-02-26 01:02:56 +00005417PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005418PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5419 Py_ssize_t size,
5420 const char *errors,
5421 int byteorder)
5422{
5423 PyObject *result;
5424 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5425 if (tmp == NULL)
5426 return NULL;
5427 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5428 Py_DECREF(tmp);
5429 return result;
5430}
5431
5432PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005433PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005434{
Victor Stinnerb960b342011-11-20 19:12:52 +01005435 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005436}
5437
Guido van Rossumd57fd912000-03-10 22:53:23 +00005438/* --- UTF-16 Codec ------------------------------------------------------- */
5439
Tim Peters772747b2001-08-09 22:21:55 +00005440PyObject *
5441PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005442 Py_ssize_t size,
5443 const char *errors,
5444 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445{
Walter Dörwald69652032004-09-07 20:24:22 +00005446 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5447}
5448
5449PyObject *
5450PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005451 Py_ssize_t size,
5452 const char *errors,
5453 int *byteorder,
5454 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005455{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005456 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005457 Py_ssize_t startinpos;
5458 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005459 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005460 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005461 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005462 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005463 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005464 PyObject *errorHandler = NULL;
5465 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005466 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005467
Tim Peters772747b2001-08-09 22:21:55 +00005468 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005469 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005470
5471 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005472 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005473
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005474 /* Check for BOM marks (U+FEFF) in the input and adjust current
5475 byte order setting accordingly. In native mode, the leading BOM
5476 mark is skipped, in all other modes, it is copied to the output
5477 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005478 if (bo == 0 && size >= 2) {
5479 const Py_UCS4 bom = (q[1] << 8) | q[0];
5480 if (bom == 0xFEFF) {
5481 q += 2;
5482 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005484 else if (bom == 0xFFFE) {
5485 q += 2;
5486 bo = 1;
5487 }
5488 if (byteorder)
5489 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005490 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491
Antoine Pitrou63065d72012-05-15 23:48:04 +02005492 if (q == e) {
5493 if (consumed)
5494 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005495 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005496 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005497
Christian Heimes743e0cd2012-10-17 23:52:17 +02005498#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005499 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005500 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005501#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005502 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005503 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005504#endif
Tim Peters772747b2001-08-09 22:21:55 +00005505
Antoine Pitrou63065d72012-05-15 23:48:04 +02005506 /* Note: size will always be longer than the resulting Unicode
5507 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005508 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005509 writer.min_length = (e - q + 1) / 2;
5510 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005511 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005512
Antoine Pitrou63065d72012-05-15 23:48:04 +02005513 while (1) {
5514 Py_UCS4 ch = 0;
5515 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005516 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005517 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005518 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005519 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005520 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005521 native_ordering);
5522 else
5523 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005524 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005525 native_ordering);
5526 } else if (kind == PyUnicode_2BYTE_KIND) {
5527 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005528 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005529 native_ordering);
5530 } else {
5531 assert(kind == PyUnicode_4BYTE_KIND);
5532 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005533 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005534 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005535 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005536 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005537
Antoine Pitrou63065d72012-05-15 23:48:04 +02005538 switch (ch)
5539 {
5540 case 0:
5541 /* remaining byte at the end? (size should be even) */
5542 if (q == e || consumed)
5543 goto End;
5544 errmsg = "truncated data";
5545 startinpos = ((const char *)q) - starts;
5546 endinpos = ((const char *)e) - starts;
5547 break;
5548 /* The remaining input chars are ignored if the callback
5549 chooses to skip the input */
5550 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005551 q -= 2;
5552 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005553 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005554 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005555 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005556 endinpos = ((const char *)e) - starts;
5557 break;
5558 case 2:
5559 errmsg = "illegal encoding";
5560 startinpos = ((const char *)q) - 2 - starts;
5561 endinpos = startinpos + 2;
5562 break;
5563 case 3:
5564 errmsg = "illegal UTF-16 surrogate";
5565 startinpos = ((const char *)q) - 4 - starts;
5566 endinpos = startinpos + 2;
5567 break;
5568 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005569 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005570 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 continue;
5572 }
5573
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005574 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005575 errors,
5576 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005577 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005578 &starts,
5579 (const char **)&e,
5580 &startinpos,
5581 &endinpos,
5582 &exc,
5583 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005584 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586 }
5587
Antoine Pitrou63065d72012-05-15 23:48:04 +02005588End:
Walter Dörwald69652032004-09-07 20:24:22 +00005589 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005591
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005592 Py_XDECREF(errorHandler);
5593 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005594 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005595
Benjamin Peterson29060642009-01-31 22:14:21 +00005596 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005597 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005598 Py_XDECREF(errorHandler);
5599 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005600 return NULL;
5601}
5602
Tim Peters772747b2001-08-09 22:21:55 +00005603PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005604_PyUnicode_EncodeUTF16(PyObject *str,
5605 const char *errors,
5606 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005607{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005608 enum PyUnicode_Kind kind;
5609 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005610 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005611 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005612 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005613 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005614#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005615 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005616#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005617 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005618#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005619 const char *encoding;
5620 Py_ssize_t nsize, pos;
5621 PyObject *errorHandler = NULL;
5622 PyObject *exc = NULL;
5623 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005624
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005625 if (!PyUnicode_Check(str)) {
5626 PyErr_BadArgument();
5627 return NULL;
5628 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005629 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005630 return NULL;
5631 kind = PyUnicode_KIND(str);
5632 data = PyUnicode_DATA(str);
5633 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005634
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005635 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005636 if (kind == PyUnicode_4BYTE_KIND) {
5637 const Py_UCS4 *in = (const Py_UCS4 *)data;
5638 const Py_UCS4 *end = in + len;
5639 while (in < end)
5640 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005641 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005642 }
5643 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005644 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 nsize = len + pairs + (byteorder == 0);
5646 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647 if (v == NULL)
5648 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005650 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005651 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005652 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005653 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005654 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005655 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005656 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005657
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005658 if (kind == PyUnicode_1BYTE_KIND) {
5659 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5660 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005661 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005662
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005663 if (byteorder < 0)
5664 encoding = "utf-16-le";
5665 else if (byteorder > 0)
5666 encoding = "utf-16-be";
5667 else
5668 encoding = "utf-16";
5669
5670 pos = 0;
5671 while (pos < len) {
5672 Py_ssize_t repsize, moreunits;
5673
5674 if (kind == PyUnicode_2BYTE_KIND) {
5675 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5676 &out, native_ordering);
5677 }
5678 else {
5679 assert(kind == PyUnicode_4BYTE_KIND);
5680 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5681 &out, native_ordering);
5682 }
5683 if (pos == len)
5684 break;
5685
5686 rep = unicode_encode_call_errorhandler(
5687 errors, &errorHandler,
5688 encoding, "surrogates not allowed",
5689 str, &exc, pos, pos + 1, &pos);
5690 if (!rep)
5691 goto error;
5692
5693 if (PyBytes_Check(rep)) {
5694 repsize = PyBytes_GET_SIZE(rep);
5695 if (repsize & 1) {
5696 raise_encode_exception(&exc, encoding,
5697 str, pos - 1, pos,
5698 "surrogates not allowed");
5699 goto error;
5700 }
5701 moreunits = repsize / 2;
5702 }
5703 else {
5704 assert(PyUnicode_Check(rep));
5705 if (PyUnicode_READY(rep) < 0)
5706 goto error;
5707 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5708 if (!PyUnicode_IS_ASCII(rep)) {
5709 raise_encode_exception(&exc, encoding,
5710 str, pos - 1, pos,
5711 "surrogates not allowed");
5712 goto error;
5713 }
5714 }
5715
5716 /* two bytes are reserved for each surrogate */
5717 if (moreunits > 1) {
5718 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5719 Py_ssize_t morebytes = 2 * (moreunits - 1);
5720 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5721 /* integer overflow */
5722 PyErr_NoMemory();
5723 goto error;
5724 }
5725 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5726 goto error;
5727 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5728 }
5729
5730 if (PyBytes_Check(rep)) {
5731 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5732 out += moreunits;
5733 } else /* rep is unicode */ {
5734 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5735 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5736 &out, native_ordering);
5737 }
5738
5739 Py_CLEAR(rep);
5740 }
5741
5742 /* Cut back to size actually needed. This is necessary for, for example,
5743 encoding of a string containing isolated surrogates and the 'ignore' handler
5744 is used. */
5745 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5746 if (nsize != PyBytes_GET_SIZE(v))
5747 _PyBytes_Resize(&v, nsize);
5748 Py_XDECREF(errorHandler);
5749 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005750 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005751 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005752 error:
5753 Py_XDECREF(rep);
5754 Py_XDECREF(errorHandler);
5755 Py_XDECREF(exc);
5756 Py_XDECREF(v);
5757 return NULL;
5758#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759}
5760
Alexander Belopolsky40018472011-02-26 01:02:56 +00005761PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005762PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5763 Py_ssize_t size,
5764 const char *errors,
5765 int byteorder)
5766{
5767 PyObject *result;
5768 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5769 if (tmp == NULL)
5770 return NULL;
5771 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5772 Py_DECREF(tmp);
5773 return result;
5774}
5775
5776PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005777PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005779 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780}
5781
5782/* --- Unicode Escape Codec ----------------------------------------------- */
5783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005784/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5785 if all the escapes in the string make it still a valid ASCII string.
5786 Returns -1 if any escapes were found which cause the string to
5787 pop out of ASCII range. Otherwise returns the length of the
5788 required buffer to hold the string.
5789 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005790static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005791length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5792{
5793 const unsigned char *p = (const unsigned char *)s;
5794 const unsigned char *end = p + size;
5795 Py_ssize_t length = 0;
5796
5797 if (size < 0)
5798 return -1;
5799
5800 for (; p < end; ++p) {
5801 if (*p > 127) {
5802 /* Non-ASCII */
5803 return -1;
5804 }
5805 else if (*p != '\\') {
5806 /* Normal character */
5807 ++length;
5808 }
5809 else {
5810 /* Backslash-escape, check next char */
5811 ++p;
5812 /* Escape sequence reaches till end of string or
5813 non-ASCII follow-up. */
5814 if (p >= end || *p > 127)
5815 return -1;
5816 switch (*p) {
5817 case '\n':
5818 /* backslash + \n result in zero characters */
5819 break;
5820 case '\\': case '\'': case '\"':
5821 case 'b': case 'f': case 't':
5822 case 'n': case 'r': case 'v': case 'a':
5823 ++length;
5824 break;
5825 case '0': case '1': case '2': case '3':
5826 case '4': case '5': case '6': case '7':
5827 case 'x': case 'u': case 'U': case 'N':
5828 /* these do not guarantee ASCII characters */
5829 return -1;
5830 default:
5831 /* count the backslash + the other character */
5832 length += 2;
5833 }
5834 }
5835 }
5836 return length;
5837}
5838
Fredrik Lundh06d12682001-01-24 07:59:11 +00005839static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005840
Alexander Belopolsky40018472011-02-26 01:02:56 +00005841PyObject *
5842PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005843 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005844 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005846 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005847 Py_ssize_t startinpos;
5848 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005849 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005850 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005851 char* message;
5852 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853 PyObject *errorHandler = NULL;
5854 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005855 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005856
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005857 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005858 if (len == 0)
5859 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005860
5861 /* After length_of_escaped_ascii_string() there are two alternatives,
5862 either the string is pure ASCII with named escapes like \n, etc.
5863 and we determined it's exact size (common case)
5864 or it contains \x, \u, ... escape sequences. then we create a
5865 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005866 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005867 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005868 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005869 }
5870 else {
5871 /* Escaped strings will always be longer than the resulting
5872 Unicode string, so we start with size here and then reduce the
5873 length after conversion to the true value.
5874 (but if the error callback returns a long replacement string
5875 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005876 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005877 }
5878
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005880 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005882
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883 while (s < end) {
5884 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005885 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005886 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887
5888 /* Non-escape characters are interpreted as Unicode ordinals */
5889 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005890 x = (unsigned char)*s;
5891 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005892 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005893 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894 continue;
5895 }
5896
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005897 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 /* \ - Escapes */
5899 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005900 c = *s++;
5901 if (s > end)
5902 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005903
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005904 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905
Benjamin Peterson29060642009-01-31 22:14:21 +00005906 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005907#define WRITECHAR(ch) \
5908 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005909 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005910 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005911 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005912
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005914 case '\\': WRITECHAR('\\'); break;
5915 case '\'': WRITECHAR('\''); break;
5916 case '\"': WRITECHAR('\"'); break;
5917 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005918 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005919 case 'f': WRITECHAR('\014'); break;
5920 case 't': WRITECHAR('\t'); break;
5921 case 'n': WRITECHAR('\n'); break;
5922 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005923 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005924 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005925 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005926 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 case '0': case '1': case '2': case '3':
5930 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005931 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005932 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005933 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005934 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005935 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005937 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938 break;
5939
Benjamin Peterson29060642009-01-31 22:14:21 +00005940 /* hex escapes */
5941 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005943 digits = 2;
5944 message = "truncated \\xXX escape";
5945 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946
Benjamin Peterson29060642009-01-31 22:14:21 +00005947 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005949 digits = 4;
5950 message = "truncated \\uXXXX escape";
5951 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952
Benjamin Peterson29060642009-01-31 22:14:21 +00005953 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005954 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005955 digits = 8;
5956 message = "truncated \\UXXXXXXXX escape";
5957 hexescape:
5958 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005959 if (end - s < digits) {
5960 /* count only hex digits */
5961 for (; s < end; ++s) {
5962 c = (unsigned char)*s;
5963 if (!Py_ISXDIGIT(c))
5964 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005965 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005966 goto error;
5967 }
5968 for (; digits--; ++s) {
5969 c = (unsigned char)*s;
5970 if (!Py_ISXDIGIT(c))
5971 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005972 chr = (chr<<4) & ~0xF;
5973 if (c >= '0' && c <= '9')
5974 chr += c - '0';
5975 else if (c >= 'a' && c <= 'f')
5976 chr += 10 + c - 'a';
5977 else
5978 chr += 10 + c - 'A';
5979 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005980 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005981 /* _decoding_error will have already written into the
5982 target buffer. */
5983 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005984 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005985 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005986 message = "illegal Unicode character";
5987 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005988 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005989 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005990 break;
5991
Benjamin Peterson29060642009-01-31 22:14:21 +00005992 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005993 case 'N':
5994 message = "malformed \\N character escape";
5995 if (ucnhash_CAPI == NULL) {
5996 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005997 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5998 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005999 if (ucnhash_CAPI == NULL)
6000 goto ucnhashError;
6001 }
6002 if (*s == '{') {
6003 const char *start = s+1;
6004 /* look for the closing brace */
6005 while (*s != '}' && s < end)
6006 s++;
6007 if (s > start && s < end && *s == '}') {
6008 /* found a name. look it up in the unicode database */
6009 message = "unknown Unicode character name";
6010 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02006011 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02006012 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006013 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006014 goto store;
6015 }
6016 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006017 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006018
6019 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006020 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 message = "\\ at end of string";
6022 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02006023 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00006024 }
6025 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006026 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02006027 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006028 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006029 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006031 continue;
6032
6033 error:
6034 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006035 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006036 errors, &errorHandler,
6037 "unicodeescape", message,
6038 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006039 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02006040 goto onError;
6041 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006043#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006044
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006045 Py_XDECREF(errorHandler);
6046 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006047 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006048
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006050 PyErr_SetString(
6051 PyExc_UnicodeError,
6052 "\\N escapes not supported (can't load unicodedata module)"
6053 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006054 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006055 Py_XDECREF(errorHandler);
6056 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006057 return NULL;
6058
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006060 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006061 Py_XDECREF(errorHandler);
6062 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 return NULL;
6064}
6065
6066/* Return a Unicode-Escape string version of the Unicode object.
6067
6068 If quotes is true, the string is enclosed in u"" or u'' quotes as
6069 appropriate.
6070
6071*/
6072
Alexander Belopolsky40018472011-02-26 01:02:56 +00006073PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006074PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006076 Py_ssize_t i, len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 int kind;
6079 void *data;
Victor Stinner358af132015-10-12 22:36:57 +02006080 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081
Ezio Melottie7f90372012-10-05 03:33:31 +03006082 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006083 escape.
6084
Ezio Melottie7f90372012-10-05 03:33:31 +03006085 For UCS1 strings it's '\xxx', 4 bytes per source character.
6086 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6087 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006088 */
6089
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006090 if (!PyUnicode_Check(unicode)) {
6091 PyErr_BadArgument();
6092 return NULL;
6093 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006094 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006095 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006096
6097 _PyBytesWriter_Init(&writer);
6098
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006099 len = PyUnicode_GET_LENGTH(unicode);
6100 kind = PyUnicode_KIND(unicode);
6101 data = PyUnicode_DATA(unicode);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006102
Victor Stinner358af132015-10-12 22:36:57 +02006103 p = _PyBytesWriter_Alloc(&writer, len);
6104 if (p == NULL)
6105 goto error;
6106 writer.overallocate = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006108 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006109 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006110
Walter Dörwald79e913e2007-05-12 11:08:06 +00006111 /* Escape backslashes */
6112 if (ch == '\\') {
Victor Stinner358af132015-10-12 22:36:57 +02006113 /* -1: substract 1 preallocated byte */
6114 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6115 if (p == NULL)
6116 goto error;
6117
Guido van Rossumd57fd912000-03-10 22:53:23 +00006118 *p++ = '\\';
6119 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006120 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006121 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006122
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006123 /* Map 21-bit characters to '\U00xxxxxx' */
6124 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006125 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006126
6127 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6128 if (p == NULL)
6129 goto error;
6130
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006131 *p++ = '\\';
6132 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006133 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6134 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6135 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6136 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6137 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6138 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6139 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6140 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006141 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006142 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006143
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006145 if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006146 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6147 if (p == NULL)
6148 goto error;
6149
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 *p++ = '\\';
6151 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006152 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6153 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6154 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6155 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006157
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006158 /* Map special whitespace to '\t', \n', '\r' */
6159 else if (ch == '\t') {
Victor Stinner358af132015-10-12 22:36:57 +02006160 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6161 if (p == NULL)
6162 goto error;
6163
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006164 *p++ = '\\';
6165 *p++ = 't';
6166 }
6167 else if (ch == '\n') {
Victor Stinner358af132015-10-12 22:36:57 +02006168 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6169 if (p == NULL)
6170 goto error;
6171
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006172 *p++ = '\\';
6173 *p++ = 'n';
6174 }
6175 else if (ch == '\r') {
Victor Stinner358af132015-10-12 22:36:57 +02006176 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6177 if (p == NULL)
6178 goto error;
6179
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006180 *p++ = '\\';
6181 *p++ = 'r';
6182 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006183
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006184 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006185 else if (ch < ' ' || ch >= 0x7F) {
Victor Stinner358af132015-10-12 22:36:57 +02006186 /* -1: substract 1 preallocated byte */
6187 p = _PyBytesWriter_Prepare(&writer, p, 4-1);
6188 if (p == NULL)
6189 goto error;
6190
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006192 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006193 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6194 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006195 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006196
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197 /* Copy everything else as-is */
6198 else
6199 *p++ = (char) ch;
6200 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201
Victor Stinner358af132015-10-12 22:36:57 +02006202 return _PyBytesWriter_Finish(&writer, p);
6203
6204error:
6205 _PyBytesWriter_Dealloc(&writer);
6206 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207}
6208
Alexander Belopolsky40018472011-02-26 01:02:56 +00006209PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006210PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6211 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006213 PyObject *result;
6214 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6215 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006217 result = PyUnicode_AsUnicodeEscapeString(tmp);
6218 Py_DECREF(tmp);
6219 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220}
6221
6222/* --- Raw Unicode Escape Codec ------------------------------------------- */
6223
Alexander Belopolsky40018472011-02-26 01:02:56 +00006224PyObject *
6225PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006226 Py_ssize_t size,
6227 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006229 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006230 Py_ssize_t startinpos;
6231 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006232 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233 const char *end;
6234 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006235 PyObject *errorHandler = NULL;
6236 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006237
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006238 if (size == 0)
6239 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006240
Guido van Rossumd57fd912000-03-10 22:53:23 +00006241 /* Escaped strings will always be longer than the resulting
6242 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006243 length after conversion to the true value. (But decoding error
6244 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006245 _PyUnicodeWriter_Init(&writer);
6246 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006247
Guido van Rossumd57fd912000-03-10 22:53:23 +00006248 end = s + size;
6249 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006250 unsigned char c;
6251 Py_UCS4 x;
6252 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006253 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 /* Non-escape characters are interpreted as Unicode ordinals */
6256 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006257 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006258 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006259 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006260 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006261 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 startinpos = s-starts;
6263
6264 /* \u-escapes are only interpreted iff the number of leading
6265 backslashes if odd */
6266 bs = s;
6267 for (;s < end;) {
6268 if (*s != '\\')
6269 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006270 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006271 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006272 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 }
6274 if (((s - bs) & 1) == 0 ||
6275 s >= end ||
6276 (*s != 'u' && *s != 'U')) {
6277 continue;
6278 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006279 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 count = *s=='u' ? 4 : 8;
6281 s++;
6282
6283 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006284 for (x = 0, i = 0; i < count; ++i, ++s) {
6285 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006286 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006288 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 errors, &errorHandler,
6290 "rawunicodeescape", "truncated \\uXXXX",
6291 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006292 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006293 goto onError;
6294 goto nextByte;
6295 }
6296 x = (x<<4) & ~0xF;
6297 if (c >= '0' && c <= '9')
6298 x += c - '0';
6299 else if (c >= 'a' && c <= 'f')
6300 x += 10 + c - 'a';
6301 else
6302 x += 10 + c - 'A';
6303 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006304 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006305 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006306 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006307 }
6308 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006309 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006310 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006311 errors, &errorHandler,
6312 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006314 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006316 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 nextByte:
6318 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006319 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320 Py_XDECREF(errorHandler);
6321 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006322 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006323
Benjamin Peterson29060642009-01-31 22:14:21 +00006324 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006325 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 Py_XDECREF(errorHandler);
6327 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328 return NULL;
6329}
6330
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006331
Alexander Belopolsky40018472011-02-26 01:02:56 +00006332PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006333PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006335 char *p;
Victor Stinner358af132015-10-12 22:36:57 +02006336 Py_ssize_t pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006337 int kind;
6338 void *data;
6339 Py_ssize_t len;
Victor Stinner358af132015-10-12 22:36:57 +02006340 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006342 if (!PyUnicode_Check(unicode)) {
6343 PyErr_BadArgument();
6344 return NULL;
6345 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006346 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006347 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006348
6349 _PyBytesWriter_Init(&writer);
6350
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006351 kind = PyUnicode_KIND(unicode);
6352 data = PyUnicode_DATA(unicode);
6353 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner0e368262011-11-10 20:12:49 +01006354
Victor Stinner358af132015-10-12 22:36:57 +02006355 p = _PyBytesWriter_Alloc(&writer, len);
6356 if (p == NULL)
6357 goto error;
6358 writer.overallocate = 1;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006359
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006360 for (pos = 0; pos < len; pos++) {
6361 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006362 /* Map 32-bit characters to '\Uxxxxxxxx' */
6363 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006364 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006365
6366 /* -1: substract 1 preallocated byte */
6367 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6368 if (p == NULL)
6369 goto error;
6370
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006371 *p++ = '\\';
6372 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006373 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6375 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6376 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6377 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6378 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6379 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6380 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006381 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006382 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006383 else if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006384 /* -1: substract 1 preallocated byte */
6385 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6386 if (p == NULL)
6387 goto error;
6388
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389 *p++ = '\\';
6390 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006391 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6392 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6393 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6394 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 /* Copy everything else as-is */
6397 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006398 *p++ = (char) ch;
6399 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006400
Victor Stinner358af132015-10-12 22:36:57 +02006401 return _PyBytesWriter_Finish(&writer, p);
6402
6403error:
6404 _PyBytesWriter_Dealloc(&writer);
6405 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406}
6407
Alexander Belopolsky40018472011-02-26 01:02:56 +00006408PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006409PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6410 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006412 PyObject *result;
6413 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6414 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006415 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006416 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6417 Py_DECREF(tmp);
6418 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006419}
6420
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006421/* --- Unicode Internal Codec ------------------------------------------- */
6422
Alexander Belopolsky40018472011-02-26 01:02:56 +00006423PyObject *
6424_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006425 Py_ssize_t size,
6426 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006427{
6428 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006429 Py_ssize_t startinpos;
6430 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006431 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006432 const char *end;
6433 const char *reason;
6434 PyObject *errorHandler = NULL;
6435 PyObject *exc = NULL;
6436
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006437 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006438 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006439 1))
6440 return NULL;
6441
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006442 if (size == 0)
6443 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006444
Victor Stinner8f674cc2013-04-17 23:02:17 +02006445 _PyUnicodeWriter_Init(&writer);
6446 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6447 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006448 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006449 }
6450 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006451
Victor Stinner8f674cc2013-04-17 23:02:17 +02006452 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006453 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006454 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006455 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006456 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006457 endinpos = end-starts;
6458 reason = "truncated input";
6459 goto error;
6460 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006461 /* We copy the raw representation one byte at a time because the
6462 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006463 ((char *) &uch)[0] = s[0];
6464 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006465#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006466 ((char *) &uch)[2] = s[2];
6467 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006468#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006469 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006470#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006471 /* We have to sanity check the raw data, otherwise doom looms for
6472 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006473 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006474 endinpos = s - starts + Py_UNICODE_SIZE;
6475 reason = "illegal code point (> 0x10FFFF)";
6476 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006477 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006478#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006479 s += Py_UNICODE_SIZE;
6480#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006481 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006482 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006483 Py_UNICODE uch2;
6484 ((char *) &uch2)[0] = s[0];
6485 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006486 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006487 {
Victor Stinner551ac952011-11-29 22:58:13 +01006488 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006489 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006490 }
6491 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006492#endif
6493
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006494 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006495 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006496 continue;
6497
6498 error:
6499 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006500 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006501 errors, &errorHandler,
6502 "unicode_internal", reason,
6503 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006504 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006505 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 }
6507
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006508 Py_XDECREF(errorHandler);
6509 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006510 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006511
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006513 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006514 Py_XDECREF(errorHandler);
6515 Py_XDECREF(exc);
6516 return NULL;
6517}
6518
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519/* --- Latin-1 Codec ------------------------------------------------------ */
6520
Alexander Belopolsky40018472011-02-26 01:02:56 +00006521PyObject *
6522PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006523 Py_ssize_t size,
6524 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006526 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006527 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006528}
6529
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006530/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006531static void
6532make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006533 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006534 PyObject *unicode,
6535 Py_ssize_t startpos, Py_ssize_t endpos,
6536 const char *reason)
6537{
6538 if (*exceptionObject == NULL) {
6539 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006540 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006541 encoding, unicode, startpos, endpos, reason);
6542 }
6543 else {
6544 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6545 goto onError;
6546 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6547 goto onError;
6548 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6549 goto onError;
6550 return;
6551 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006552 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006553 }
6554}
6555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006556/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006557static void
6558raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006559 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006560 PyObject *unicode,
6561 Py_ssize_t startpos, Py_ssize_t endpos,
6562 const char *reason)
6563{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006564 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006565 encoding, unicode, startpos, endpos, reason);
6566 if (*exceptionObject != NULL)
6567 PyCodec_StrictErrors(*exceptionObject);
6568}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006569
6570/* error handling callback helper:
6571 build arguments, call the callback and check the arguments,
6572 put the result into newpos and return the replacement string, which
6573 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006574static PyObject *
6575unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006576 PyObject **errorHandler,
6577 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006579 Py_ssize_t startpos, Py_ssize_t endpos,
6580 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006582 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584 PyObject *restuple;
6585 PyObject *resunicode;
6586
6587 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006591 }
6592
Benjamin Petersonbac79492012-01-14 13:34:47 -05006593 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006594 return NULL;
6595 len = PyUnicode_GET_LENGTH(unicode);
6596
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006597 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601
6602 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006606 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006607 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 Py_DECREF(restuple);
6609 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006610 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006611 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006612 &resunicode, newpos)) {
6613 Py_DECREF(restuple);
6614 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006615 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006616 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6617 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6618 Py_DECREF(restuple);
6619 return NULL;
6620 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006621 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622 *newpos = len + *newpos;
6623 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006624 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006625 Py_DECREF(restuple);
6626 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006627 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 Py_INCREF(resunicode);
6629 Py_DECREF(restuple);
6630 return resunicode;
6631}
6632
Alexander Belopolsky40018472011-02-26 01:02:56 +00006633static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006634unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006635 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006636 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006638 /* input state */
6639 Py_ssize_t pos=0, size;
6640 int kind;
6641 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 /* pointer into the output */
6643 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006644 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6645 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006646 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006648 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006649 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006650 /* output object */
6651 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652
Benjamin Petersonbac79492012-01-14 13:34:47 -05006653 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 return NULL;
6655 size = PyUnicode_GET_LENGTH(unicode);
6656 kind = PyUnicode_KIND(unicode);
6657 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006658 /* allocate enough for a simple encoding without
6659 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006660 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006661 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006662
6663 _PyBytesWriter_Init(&writer);
6664 str = _PyBytesWriter_Alloc(&writer, size);
6665 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006666 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006668 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006669 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670
Benjamin Peterson29060642009-01-31 22:14:21 +00006671 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006672 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006674 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006675 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006676 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006677 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006678 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006679 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006680 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006681 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006682 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006683
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006684 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006685 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006686
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006687 /* Only overallocate the buffer if it's not the last write */
6688 writer.overallocate = (collend < size);
6689
Benjamin Peterson29060642009-01-31 22:14:21 +00006690 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006691 if (error_handler == _Py_ERROR_UNKNOWN)
6692 error_handler = get_error_handler(errors);
6693
6694 switch (error_handler) {
6695 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006696 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006697 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006698
6699 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006700 memset(str, '?', collend - collstart);
6701 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006702 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006703 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006704 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 break;
Victor Stinner50149202015-09-22 00:26:54 +02006706
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006707 case _Py_ERROR_BACKSLASHREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006708 /* substract preallocated bytes */
6709 writer.min_size -= (collend - collstart);
6710 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006711 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006712 if (str == NULL)
6713 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006714 pos = collend;
6715 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006716
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006717 case _Py_ERROR_XMLCHARREFREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006718 /* substract preallocated bytes */
6719 writer.min_size -= (collend - collstart);
6720 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006721 unicode, collstart, collend);
6722 if (str == NULL)
6723 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006724 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 break;
Victor Stinner50149202015-09-22 00:26:54 +02006726
Victor Stinnerc3713e92015-09-29 12:32:13 +02006727 case _Py_ERROR_SURROGATEESCAPE:
6728 for (i = collstart; i < collend; ++i) {
6729 ch = PyUnicode_READ(kind, data, i);
6730 if (ch < 0xdc80 || 0xdcff < ch) {
6731 /* Not a UTF-8b surrogate */
6732 break;
6733 }
6734 *str++ = (char)(ch - 0xdc00);
6735 ++pos;
6736 }
6737 if (i >= collend)
6738 break;
6739 collstart = pos;
6740 assert(collstart != collend);
6741 /* fallback to general error handling */
6742
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006744 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6745 encoding, reason, unicode, &exc,
6746 collstart, collend, &newpos);
6747 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006749
Victor Stinnerad771582015-10-09 12:38:53 +02006750 /* substract preallocated bytes */
6751 writer.min_size -= 1;
6752
Victor Stinner6bd525b2015-10-09 13:10:05 +02006753 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006754 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006755 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006756 PyBytes_AS_STRING(rep),
6757 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006758 if (str == NULL)
6759 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006760 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006761 else {
6762 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006763
Victor Stinner6bd525b2015-10-09 13:10:05 +02006764 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006766
6767 if (PyUnicode_IS_ASCII(rep)) {
6768 /* Fast path: all characters are smaller than limit */
6769 assert(limit >= 128);
6770 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6771 str = _PyBytesWriter_WriteBytes(&writer, str,
6772 PyUnicode_DATA(rep),
6773 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006775 else {
6776 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6777
6778 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6779 if (str == NULL)
6780 goto onError;
6781
6782 /* check if there is anything unencodable in the
6783 replacement and copy it to the output */
6784 for (i = 0; repsize-->0; ++i, ++str) {
6785 ch = PyUnicode_READ_CHAR(rep, i);
6786 if (ch >= limit) {
6787 raise_encode_exception(&exc, encoding, unicode,
6788 pos, pos+1, reason);
6789 goto onError;
6790 }
6791 *str = (char)ch;
6792 }
6793 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006795 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006796 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006797 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006798
6799 /* If overallocation was disabled, ensure that it was the last
6800 write. Otherwise, we missed an optimization */
6801 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006802 }
6803 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006804
Victor Stinner50149202015-09-22 00:26:54 +02006805 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006806 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006807 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006808
6809 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006810 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006811 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006812 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006813 Py_XDECREF(exc);
6814 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006815}
6816
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006817/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006818PyObject *
6819PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006820 Py_ssize_t size,
6821 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006822{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006823 PyObject *result;
6824 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6825 if (unicode == NULL)
6826 return NULL;
6827 result = unicode_encode_ucs1(unicode, errors, 256);
6828 Py_DECREF(unicode);
6829 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006830}
6831
Alexander Belopolsky40018472011-02-26 01:02:56 +00006832PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006833_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006834{
6835 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006836 PyErr_BadArgument();
6837 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006838 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006839 if (PyUnicode_READY(unicode) == -1)
6840 return NULL;
6841 /* Fast path: if it is a one-byte string, construct
6842 bytes object directly. */
6843 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6844 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6845 PyUnicode_GET_LENGTH(unicode));
6846 /* Non-Latin-1 characters present. Defer to above function to
6847 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006848 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006849}
6850
6851PyObject*
6852PyUnicode_AsLatin1String(PyObject *unicode)
6853{
6854 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006855}
6856
6857/* --- 7-bit ASCII Codec -------------------------------------------------- */
6858
Alexander Belopolsky40018472011-02-26 01:02:56 +00006859PyObject *
6860PyUnicode_DecodeASCII(const char *s,
6861 Py_ssize_t size,
6862 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006863{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006864 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006865 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006866 int kind;
6867 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006868 Py_ssize_t startinpos;
6869 Py_ssize_t endinpos;
6870 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006871 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006872 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006873 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006874 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006875
Guido van Rossumd57fd912000-03-10 22:53:23 +00006876 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006877 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006878
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006880 if (size == 1 && (unsigned char)s[0] < 128)
6881 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006882
Victor Stinner8f674cc2013-04-17 23:02:17 +02006883 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006884 writer.min_length = size;
6885 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006886 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006887
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006888 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006889 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006890 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006891 writer.pos = outpos;
6892 if (writer.pos == size)
6893 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006894
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006895 s += writer.pos;
6896 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006897 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006898 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006899 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006900 PyUnicode_WRITE(kind, data, writer.pos, c);
6901 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006902 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006903 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006904 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006905
6906 /* byte outsize range 0x00..0x7f: call the error handler */
6907
6908 if (error_handler == _Py_ERROR_UNKNOWN)
6909 error_handler = get_error_handler(errors);
6910
6911 switch (error_handler)
6912 {
6913 case _Py_ERROR_REPLACE:
6914 case _Py_ERROR_SURROGATEESCAPE:
6915 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006916 but we may switch to UCS2 at the first write */
6917 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6918 goto onError;
6919 kind = writer.kind;
6920 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006921
6922 if (error_handler == _Py_ERROR_REPLACE)
6923 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6924 else
6925 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6926 writer.pos++;
6927 ++s;
6928 break;
6929
6930 case _Py_ERROR_IGNORE:
6931 ++s;
6932 break;
6933
6934 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 startinpos = s-starts;
6936 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006937 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006938 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 "ascii", "ordinal not in range(128)",
6940 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006941 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006942 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006943 kind = writer.kind;
6944 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006945 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006946 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006947 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006948 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006949 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006950
Benjamin Peterson29060642009-01-31 22:14:21 +00006951 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006952 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006953 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006954 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006955 return NULL;
6956}
6957
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006958/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006959PyObject *
6960PyUnicode_EncodeASCII(const Py_UNICODE *p,
6961 Py_ssize_t size,
6962 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006963{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006964 PyObject *result;
6965 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6966 if (unicode == NULL)
6967 return NULL;
6968 result = unicode_encode_ucs1(unicode, errors, 128);
6969 Py_DECREF(unicode);
6970 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006971}
6972
Alexander Belopolsky40018472011-02-26 01:02:56 +00006973PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006974_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006975{
6976 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006977 PyErr_BadArgument();
6978 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006979 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006980 if (PyUnicode_READY(unicode) == -1)
6981 return NULL;
6982 /* Fast path: if it is an ASCII-only string, construct bytes object
6983 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006984 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006985 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6986 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006987 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006988}
6989
6990PyObject *
6991PyUnicode_AsASCIIString(PyObject *unicode)
6992{
6993 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994}
6995
Victor Stinner99b95382011-07-04 14:23:54 +02006996#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006997
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006998/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006999
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007000#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007001#define NEED_RETRY
7002#endif
7003
Victor Stinner3a50e702011-10-18 21:21:00 +02007004#ifndef WC_ERR_INVALID_CHARS
7005# define WC_ERR_INVALID_CHARS 0x0080
7006#endif
7007
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007008static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007009code_page_name(UINT code_page, PyObject **obj)
7010{
7011 *obj = NULL;
7012 if (code_page == CP_ACP)
7013 return "mbcs";
7014 if (code_page == CP_UTF7)
7015 return "CP_UTF7";
7016 if (code_page == CP_UTF8)
7017 return "CP_UTF8";
7018
7019 *obj = PyBytes_FromFormat("cp%u", code_page);
7020 if (*obj == NULL)
7021 return NULL;
7022 return PyBytes_AS_STRING(*obj);
7023}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007024
Victor Stinner3a50e702011-10-18 21:21:00 +02007025static DWORD
7026decode_code_page_flags(UINT code_page)
7027{
7028 if (code_page == CP_UTF7) {
7029 /* The CP_UTF7 decoder only supports flags=0 */
7030 return 0;
7031 }
7032 else
7033 return MB_ERR_INVALID_CHARS;
7034}
7035
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007037 * Decode a byte string from a Windows code page into unicode object in strict
7038 * mode.
7039 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007040 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7041 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007042 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007043static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007044decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007045 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 const char *in,
7047 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007048{
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007050 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052
7053 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007054 assert(insize > 0);
7055 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7056 if (outsize <= 0)
7057 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007058
7059 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007060 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007061 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007062 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007063 if (*v == NULL)
7064 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007066 }
7067 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007068 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007070 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007071 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007072 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073 }
7074
7075 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7077 if (outsize <= 0)
7078 goto error;
7079 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007080
Victor Stinner3a50e702011-10-18 21:21:00 +02007081error:
7082 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7083 return -2;
7084 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007085 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086}
7087
Victor Stinner3a50e702011-10-18 21:21:00 +02007088/*
7089 * Decode a byte string from a code page into unicode object with an error
7090 * handler.
7091 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007092 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 * UnicodeDecodeError exception and returns -1 on error.
7094 */
7095static int
7096decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007097 PyObject **v,
7098 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007099 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007100{
7101 const char *startin = in;
7102 const char *endin = in + size;
7103 const DWORD flags = decode_code_page_flags(code_page);
7104 /* Ideally, we should get reason from FormatMessage. This is the Windows
7105 2000 English version of the message. */
7106 const char *reason = "No mapping for the Unicode character exists "
7107 "in the target code page.";
7108 /* each step cannot decode more than 1 character, but a character can be
7109 represented as a surrogate pair */
7110 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007111 int insize;
7112 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 PyObject *errorHandler = NULL;
7114 PyObject *exc = NULL;
7115 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007116 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007117 DWORD err;
7118 int ret = -1;
7119
7120 assert(size > 0);
7121
7122 encoding = code_page_name(code_page, &encoding_obj);
7123 if (encoding == NULL)
7124 return -1;
7125
Victor Stinner7d00cc12014-03-17 23:08:06 +01007126 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7128 UnicodeDecodeError. */
7129 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7130 if (exc != NULL) {
7131 PyCodec_StrictErrors(exc);
7132 Py_CLEAR(exc);
7133 }
7134 goto error;
7135 }
7136
7137 if (*v == NULL) {
7138 /* Create unicode object */
7139 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7140 PyErr_NoMemory();
7141 goto error;
7142 }
Victor Stinnerab595942011-12-17 04:59:06 +01007143 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007144 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 if (*v == NULL)
7146 goto error;
7147 startout = PyUnicode_AS_UNICODE(*v);
7148 }
7149 else {
7150 /* Extend unicode object */
7151 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7152 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7153 PyErr_NoMemory();
7154 goto error;
7155 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007156 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 goto error;
7158 startout = PyUnicode_AS_UNICODE(*v) + n;
7159 }
7160
7161 /* Decode the byte string character per character */
7162 out = startout;
7163 while (in < endin)
7164 {
7165 /* Decode a character */
7166 insize = 1;
7167 do
7168 {
7169 outsize = MultiByteToWideChar(code_page, flags,
7170 in, insize,
7171 buffer, Py_ARRAY_LENGTH(buffer));
7172 if (outsize > 0)
7173 break;
7174 err = GetLastError();
7175 if (err != ERROR_NO_UNICODE_TRANSLATION
7176 && err != ERROR_INSUFFICIENT_BUFFER)
7177 {
7178 PyErr_SetFromWindowsErr(0);
7179 goto error;
7180 }
7181 insize++;
7182 }
7183 /* 4=maximum length of a UTF-8 sequence */
7184 while (insize <= 4 && (in + insize) <= endin);
7185
7186 if (outsize <= 0) {
7187 Py_ssize_t startinpos, endinpos, outpos;
7188
Victor Stinner7d00cc12014-03-17 23:08:06 +01007189 /* last character in partial decode? */
7190 if (in + insize >= endin && !final)
7191 break;
7192
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 startinpos = in - startin;
7194 endinpos = startinpos + 1;
7195 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007196 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 errors, &errorHandler,
7198 encoding, reason,
7199 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007200 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 {
7202 goto error;
7203 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007204 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 }
7206 else {
7207 in += insize;
7208 memcpy(out, buffer, outsize * sizeof(wchar_t));
7209 out += outsize;
7210 }
7211 }
7212
7213 /* write a NUL character at the end */
7214 *out = 0;
7215
7216 /* Extend unicode object */
7217 outsize = out - startout;
7218 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007219 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007221 /* (in - startin) <= size and size is an int */
7222 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007223
7224error:
7225 Py_XDECREF(encoding_obj);
7226 Py_XDECREF(errorHandler);
7227 Py_XDECREF(exc);
7228 return ret;
7229}
7230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231static PyObject *
7232decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007233 const char *s, Py_ssize_t size,
7234 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007235{
Victor Stinner76a31a62011-11-04 00:05:13 +01007236 PyObject *v = NULL;
7237 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 if (code_page < 0) {
7240 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7241 return NULL;
7242 }
7243
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007244 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007245 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007246
Victor Stinner76a31a62011-11-04 00:05:13 +01007247 do
7248 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007249#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 if (size > INT_MAX) {
7251 chunk_size = INT_MAX;
7252 final = 0;
7253 done = 0;
7254 }
7255 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007256#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007257 {
7258 chunk_size = (int)size;
7259 final = (consumed == NULL);
7260 done = 1;
7261 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007262
Victor Stinner76a31a62011-11-04 00:05:13 +01007263 if (chunk_size == 0 && done) {
7264 if (v != NULL)
7265 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007266 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007267 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007268
Victor Stinner76a31a62011-11-04 00:05:13 +01007269 converted = decode_code_page_strict(code_page, &v,
7270 s, chunk_size);
7271 if (converted == -2)
7272 converted = decode_code_page_errors(code_page, &v,
7273 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007274 errors, final);
7275 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007276
7277 if (converted < 0) {
7278 Py_XDECREF(v);
7279 return NULL;
7280 }
7281
7282 if (consumed)
7283 *consumed += converted;
7284
7285 s += converted;
7286 size -= converted;
7287 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007288
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007289 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007290}
7291
Alexander Belopolsky40018472011-02-26 01:02:56 +00007292PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007293PyUnicode_DecodeCodePageStateful(int code_page,
7294 const char *s,
7295 Py_ssize_t size,
7296 const char *errors,
7297 Py_ssize_t *consumed)
7298{
7299 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7300}
7301
7302PyObject *
7303PyUnicode_DecodeMBCSStateful(const char *s,
7304 Py_ssize_t size,
7305 const char *errors,
7306 Py_ssize_t *consumed)
7307{
7308 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7309}
7310
7311PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007312PyUnicode_DecodeMBCS(const char *s,
7313 Py_ssize_t size,
7314 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007315{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7317}
7318
Victor Stinner3a50e702011-10-18 21:21:00 +02007319static DWORD
7320encode_code_page_flags(UINT code_page, const char *errors)
7321{
7322 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007323 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007324 }
7325 else if (code_page == CP_UTF7) {
7326 /* CP_UTF7 only supports flags=0 */
7327 return 0;
7328 }
7329 else {
7330 if (errors != NULL && strcmp(errors, "replace") == 0)
7331 return 0;
7332 else
7333 return WC_NO_BEST_FIT_CHARS;
7334 }
7335}
7336
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007337/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 * Encode a Unicode string to a Windows code page into a byte string in strict
7339 * mode.
7340 *
7341 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007342 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007343 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007344static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007345encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007346 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007347 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007348{
Victor Stinner554f3f02010-06-16 23:33:54 +00007349 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007350 BOOL *pusedDefaultChar = &usedDefaultChar;
7351 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007352 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007353 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007354 const DWORD flags = encode_code_page_flags(code_page, NULL);
7355 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007356 /* Create a substring so that we can get the UTF-16 representation
7357 of just the slice under consideration. */
7358 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007359
Martin v. Löwis3d325192011-11-04 18:23:06 +01007360 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007361
Victor Stinner3a50e702011-10-18 21:21:00 +02007362 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007363 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007365 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007366
Victor Stinner2fc507f2011-11-04 20:06:39 +01007367 substring = PyUnicode_Substring(unicode, offset, offset+len);
7368 if (substring == NULL)
7369 return -1;
7370 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7371 if (p == NULL) {
7372 Py_DECREF(substring);
7373 return -1;
7374 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007375 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007376
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007377 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007379 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 NULL, 0,
7381 NULL, pusedDefaultChar);
7382 if (outsize <= 0)
7383 goto error;
7384 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007385 if (pusedDefaultChar && *pusedDefaultChar) {
7386 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007388 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007389
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007391 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007393 if (*outbytes == NULL) {
7394 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007395 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007396 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007398 }
7399 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007400 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 const Py_ssize_t n = PyBytes_Size(*outbytes);
7402 if (outsize > PY_SSIZE_T_MAX - n) {
7403 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007404 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007405 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007407 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7408 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007410 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007412 }
7413
7414 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007416 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 out, outsize,
7418 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007419 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 if (outsize <= 0)
7421 goto error;
7422 if (pusedDefaultChar && *pusedDefaultChar)
7423 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007424 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007425
Victor Stinner3a50e702011-10-18 21:21:00 +02007426error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007427 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7429 return -2;
7430 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007431 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007432}
7433
Victor Stinner3a50e702011-10-18 21:21:00 +02007434/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007435 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 * error handler.
7437 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007438 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 * -1 on other error.
7440 */
7441static int
7442encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007443 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007444 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007445{
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 Py_ssize_t pos = unicode_offset;
7448 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 /* Ideally, we should get reason from FormatMessage. This is the Windows
7450 2000 English version of the message. */
7451 const char *reason = "invalid character";
7452 /* 4=maximum length of a UTF-8 sequence */
7453 char buffer[4];
7454 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7455 Py_ssize_t outsize;
7456 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 PyObject *errorHandler = NULL;
7458 PyObject *exc = NULL;
7459 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007460 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007461 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 PyObject *rep;
7463 int ret = -1;
7464
7465 assert(insize > 0);
7466
7467 encoding = code_page_name(code_page, &encoding_obj);
7468 if (encoding == NULL)
7469 return -1;
7470
7471 if (errors == NULL || strcmp(errors, "strict") == 0) {
7472 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7473 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007474 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 if (exc != NULL) {
7476 PyCodec_StrictErrors(exc);
7477 Py_DECREF(exc);
7478 }
7479 Py_XDECREF(encoding_obj);
7480 return -1;
7481 }
7482
7483 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7484 pusedDefaultChar = &usedDefaultChar;
7485 else
7486 pusedDefaultChar = NULL;
7487
7488 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7489 PyErr_NoMemory();
7490 goto error;
7491 }
7492 outsize = insize * Py_ARRAY_LENGTH(buffer);
7493
7494 if (*outbytes == NULL) {
7495 /* Create string object */
7496 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7497 if (*outbytes == NULL)
7498 goto error;
7499 out = PyBytes_AS_STRING(*outbytes);
7500 }
7501 else {
7502 /* Extend string object */
7503 Py_ssize_t n = PyBytes_Size(*outbytes);
7504 if (n > PY_SSIZE_T_MAX - outsize) {
7505 PyErr_NoMemory();
7506 goto error;
7507 }
7508 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7509 goto error;
7510 out = PyBytes_AS_STRING(*outbytes) + n;
7511 }
7512
7513 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007514 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007515 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007516 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7517 wchar_t chars[2];
7518 int charsize;
7519 if (ch < 0x10000) {
7520 chars[0] = (wchar_t)ch;
7521 charsize = 1;
7522 }
7523 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007524 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7525 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007526 charsize = 2;
7527 }
7528
Victor Stinner3a50e702011-10-18 21:21:00 +02007529 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007530 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007531 buffer, Py_ARRAY_LENGTH(buffer),
7532 NULL, pusedDefaultChar);
7533 if (outsize > 0) {
7534 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7535 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007536 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007537 memcpy(out, buffer, outsize);
7538 out += outsize;
7539 continue;
7540 }
7541 }
7542 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7543 PyErr_SetFromWindowsErr(0);
7544 goto error;
7545 }
7546
Victor Stinner3a50e702011-10-18 21:21:00 +02007547 rep = unicode_encode_call_errorhandler(
7548 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007549 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007550 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007551 if (rep == NULL)
7552 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007553 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007554
7555 if (PyBytes_Check(rep)) {
7556 outsize = PyBytes_GET_SIZE(rep);
7557 if (outsize != 1) {
7558 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7559 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7560 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7561 Py_DECREF(rep);
7562 goto error;
7563 }
7564 out = PyBytes_AS_STRING(*outbytes) + offset;
7565 }
7566 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7567 out += outsize;
7568 }
7569 else {
7570 Py_ssize_t i;
7571 enum PyUnicode_Kind kind;
7572 void *data;
7573
Benjamin Petersonbac79492012-01-14 13:34:47 -05007574 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 Py_DECREF(rep);
7576 goto error;
7577 }
7578
7579 outsize = PyUnicode_GET_LENGTH(rep);
7580 if (outsize != 1) {
7581 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7582 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7583 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7584 Py_DECREF(rep);
7585 goto error;
7586 }
7587 out = PyBytes_AS_STRING(*outbytes) + offset;
7588 }
7589 kind = PyUnicode_KIND(rep);
7590 data = PyUnicode_DATA(rep);
7591 for (i=0; i < outsize; i++) {
7592 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7593 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007594 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007595 encoding, unicode,
7596 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007597 "unable to encode error handler result to ASCII");
7598 Py_DECREF(rep);
7599 goto error;
7600 }
7601 *out = (unsigned char)ch;
7602 out++;
7603 }
7604 }
7605 Py_DECREF(rep);
7606 }
7607 /* write a NUL byte */
7608 *out = 0;
7609 outsize = out - PyBytes_AS_STRING(*outbytes);
7610 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7611 if (_PyBytes_Resize(outbytes, outsize) < 0)
7612 goto error;
7613 ret = 0;
7614
7615error:
7616 Py_XDECREF(encoding_obj);
7617 Py_XDECREF(errorHandler);
7618 Py_XDECREF(exc);
7619 return ret;
7620}
7621
Victor Stinner3a50e702011-10-18 21:21:00 +02007622static PyObject *
7623encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007624 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007625 const char *errors)
7626{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007627 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007628 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007629 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007630 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007631
Victor Stinner29dacf22015-01-26 16:41:32 +01007632 if (!PyUnicode_Check(unicode)) {
7633 PyErr_BadArgument();
7634 return NULL;
7635 }
7636
Benjamin Petersonbac79492012-01-14 13:34:47 -05007637 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007638 return NULL;
7639 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007640
Victor Stinner3a50e702011-10-18 21:21:00 +02007641 if (code_page < 0) {
7642 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7643 return NULL;
7644 }
7645
Martin v. Löwis3d325192011-11-04 18:23:06 +01007646 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007647 return PyBytes_FromStringAndSize(NULL, 0);
7648
Victor Stinner7581cef2011-11-03 22:32:33 +01007649 offset = 0;
7650 do
7651 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007652#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007653 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007654 chunks. */
7655 if (len > INT_MAX/2) {
7656 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007657 done = 0;
7658 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007660#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007661 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007662 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007663 done = 1;
7664 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007665
Victor Stinner76a31a62011-11-04 00:05:13 +01007666 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007667 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007668 errors);
7669 if (ret == -2)
7670 ret = encode_code_page_errors(code_page, &outbytes,
7671 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007672 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007673 if (ret < 0) {
7674 Py_XDECREF(outbytes);
7675 return NULL;
7676 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007677
Victor Stinner7581cef2011-11-03 22:32:33 +01007678 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007680 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007681
Victor Stinner3a50e702011-10-18 21:21:00 +02007682 return outbytes;
7683}
7684
7685PyObject *
7686PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7687 Py_ssize_t size,
7688 const char *errors)
7689{
Victor Stinner7581cef2011-11-03 22:32:33 +01007690 PyObject *unicode, *res;
7691 unicode = PyUnicode_FromUnicode(p, size);
7692 if (unicode == NULL)
7693 return NULL;
7694 res = encode_code_page(CP_ACP, unicode, errors);
7695 Py_DECREF(unicode);
7696 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007697}
7698
7699PyObject *
7700PyUnicode_EncodeCodePage(int code_page,
7701 PyObject *unicode,
7702 const char *errors)
7703{
Victor Stinner7581cef2011-11-03 22:32:33 +01007704 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007705}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007706
Alexander Belopolsky40018472011-02-26 01:02:56 +00007707PyObject *
7708PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007709{
Victor Stinner7581cef2011-11-03 22:32:33 +01007710 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007711}
7712
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007713#undef NEED_RETRY
7714
Victor Stinner99b95382011-07-04 14:23:54 +02007715#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007716
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717/* --- Character Mapping Codec -------------------------------------------- */
7718
Victor Stinnerfb161b12013-04-18 01:44:27 +02007719static int
7720charmap_decode_string(const char *s,
7721 Py_ssize_t size,
7722 PyObject *mapping,
7723 const char *errors,
7724 _PyUnicodeWriter *writer)
7725{
7726 const char *starts = s;
7727 const char *e;
7728 Py_ssize_t startinpos, endinpos;
7729 PyObject *errorHandler = NULL, *exc = NULL;
7730 Py_ssize_t maplen;
7731 enum PyUnicode_Kind mapkind;
7732 void *mapdata;
7733 Py_UCS4 x;
7734 unsigned char ch;
7735
7736 if (PyUnicode_READY(mapping) == -1)
7737 return -1;
7738
7739 maplen = PyUnicode_GET_LENGTH(mapping);
7740 mapdata = PyUnicode_DATA(mapping);
7741 mapkind = PyUnicode_KIND(mapping);
7742
7743 e = s + size;
7744
7745 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7746 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7747 * is disabled in encoding aliases, latin1 is preferred because
7748 * its implementation is faster. */
7749 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7750 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7751 Py_UCS4 maxchar = writer->maxchar;
7752
7753 assert (writer->kind == PyUnicode_1BYTE_KIND);
7754 while (s < e) {
7755 ch = *s;
7756 x = mapdata_ucs1[ch];
7757 if (x > maxchar) {
7758 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7759 goto onError;
7760 maxchar = writer->maxchar;
7761 outdata = (Py_UCS1 *)writer->data;
7762 }
7763 outdata[writer->pos] = x;
7764 writer->pos++;
7765 ++s;
7766 }
7767 return 0;
7768 }
7769
7770 while (s < e) {
7771 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7772 enum PyUnicode_Kind outkind = writer->kind;
7773 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7774 if (outkind == PyUnicode_1BYTE_KIND) {
7775 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7776 Py_UCS4 maxchar = writer->maxchar;
7777 while (s < e) {
7778 ch = *s;
7779 x = mapdata_ucs2[ch];
7780 if (x > maxchar)
7781 goto Error;
7782 outdata[writer->pos] = x;
7783 writer->pos++;
7784 ++s;
7785 }
7786 break;
7787 }
7788 else if (outkind == PyUnicode_2BYTE_KIND) {
7789 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7790 while (s < e) {
7791 ch = *s;
7792 x = mapdata_ucs2[ch];
7793 if (x == 0xFFFE)
7794 goto Error;
7795 outdata[writer->pos] = x;
7796 writer->pos++;
7797 ++s;
7798 }
7799 break;
7800 }
7801 }
7802 ch = *s;
7803
7804 if (ch < maplen)
7805 x = PyUnicode_READ(mapkind, mapdata, ch);
7806 else
7807 x = 0xfffe; /* invalid value */
7808Error:
7809 if (x == 0xfffe)
7810 {
7811 /* undefined mapping */
7812 startinpos = s-starts;
7813 endinpos = startinpos+1;
7814 if (unicode_decode_call_errorhandler_writer(
7815 errors, &errorHandler,
7816 "charmap", "character maps to <undefined>",
7817 &starts, &e, &startinpos, &endinpos, &exc, &s,
7818 writer)) {
7819 goto onError;
7820 }
7821 continue;
7822 }
7823
7824 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7825 goto onError;
7826 ++s;
7827 }
7828 Py_XDECREF(errorHandler);
7829 Py_XDECREF(exc);
7830 return 0;
7831
7832onError:
7833 Py_XDECREF(errorHandler);
7834 Py_XDECREF(exc);
7835 return -1;
7836}
7837
7838static int
7839charmap_decode_mapping(const char *s,
7840 Py_ssize_t size,
7841 PyObject *mapping,
7842 const char *errors,
7843 _PyUnicodeWriter *writer)
7844{
7845 const char *starts = s;
7846 const char *e;
7847 Py_ssize_t startinpos, endinpos;
7848 PyObject *errorHandler = NULL, *exc = NULL;
7849 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007850 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007851
7852 e = s + size;
7853
7854 while (s < e) {
7855 ch = *s;
7856
7857 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7858 key = PyLong_FromLong((long)ch);
7859 if (key == NULL)
7860 goto onError;
7861
7862 item = PyObject_GetItem(mapping, key);
7863 Py_DECREF(key);
7864 if (item == NULL) {
7865 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7866 /* No mapping found means: mapping is undefined. */
7867 PyErr_Clear();
7868 goto Undefined;
7869 } else
7870 goto onError;
7871 }
7872
7873 /* Apply mapping */
7874 if (item == Py_None)
7875 goto Undefined;
7876 if (PyLong_Check(item)) {
7877 long value = PyLong_AS_LONG(item);
7878 if (value == 0xFFFE)
7879 goto Undefined;
7880 if (value < 0 || value > MAX_UNICODE) {
7881 PyErr_Format(PyExc_TypeError,
7882 "character mapping must be in range(0x%lx)",
7883 (unsigned long)MAX_UNICODE + 1);
7884 goto onError;
7885 }
7886
7887 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7888 goto onError;
7889 }
7890 else if (PyUnicode_Check(item)) {
7891 if (PyUnicode_READY(item) == -1)
7892 goto onError;
7893 if (PyUnicode_GET_LENGTH(item) == 1) {
7894 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7895 if (value == 0xFFFE)
7896 goto Undefined;
7897 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7898 goto onError;
7899 }
7900 else {
7901 writer->overallocate = 1;
7902 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7903 goto onError;
7904 }
7905 }
7906 else {
7907 /* wrong return value */
7908 PyErr_SetString(PyExc_TypeError,
7909 "character mapping must return integer, None or str");
7910 goto onError;
7911 }
7912 Py_CLEAR(item);
7913 ++s;
7914 continue;
7915
7916Undefined:
7917 /* undefined mapping */
7918 Py_CLEAR(item);
7919 startinpos = s-starts;
7920 endinpos = startinpos+1;
7921 if (unicode_decode_call_errorhandler_writer(
7922 errors, &errorHandler,
7923 "charmap", "character maps to <undefined>",
7924 &starts, &e, &startinpos, &endinpos, &exc, &s,
7925 writer)) {
7926 goto onError;
7927 }
7928 }
7929 Py_XDECREF(errorHandler);
7930 Py_XDECREF(exc);
7931 return 0;
7932
7933onError:
7934 Py_XDECREF(item);
7935 Py_XDECREF(errorHandler);
7936 Py_XDECREF(exc);
7937 return -1;
7938}
7939
Alexander Belopolsky40018472011-02-26 01:02:56 +00007940PyObject *
7941PyUnicode_DecodeCharmap(const char *s,
7942 Py_ssize_t size,
7943 PyObject *mapping,
7944 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007945{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007946 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007947
Guido van Rossumd57fd912000-03-10 22:53:23 +00007948 /* Default to Latin-1 */
7949 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007950 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007951
Guido van Rossumd57fd912000-03-10 22:53:23 +00007952 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007953 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007954 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007955 writer.min_length = size;
7956 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007957 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007958
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007959 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007960 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7961 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007962 }
7963 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007964 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7965 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007966 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007967 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007968
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007970 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007971 return NULL;
7972}
7973
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007974/* Charmap encoding: the lookup table */
7975
Alexander Belopolsky40018472011-02-26 01:02:56 +00007976struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 PyObject_HEAD
7978 unsigned char level1[32];
7979 int count2, count3;
7980 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007981};
7982
7983static PyObject*
7984encoding_map_size(PyObject *obj, PyObject* args)
7985{
7986 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007987 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007989}
7990
7991static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007992 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 PyDoc_STR("Return the size (in bytes) of this object") },
7994 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007995};
7996
7997static void
7998encoding_map_dealloc(PyObject* o)
7999{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008000 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008001}
8002
8003static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008004 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 "EncodingMap", /*tp_name*/
8006 sizeof(struct encoding_map), /*tp_basicsize*/
8007 0, /*tp_itemsize*/
8008 /* methods */
8009 encoding_map_dealloc, /*tp_dealloc*/
8010 0, /*tp_print*/
8011 0, /*tp_getattr*/
8012 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008013 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 0, /*tp_repr*/
8015 0, /*tp_as_number*/
8016 0, /*tp_as_sequence*/
8017 0, /*tp_as_mapping*/
8018 0, /*tp_hash*/
8019 0, /*tp_call*/
8020 0, /*tp_str*/
8021 0, /*tp_getattro*/
8022 0, /*tp_setattro*/
8023 0, /*tp_as_buffer*/
8024 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8025 0, /*tp_doc*/
8026 0, /*tp_traverse*/
8027 0, /*tp_clear*/
8028 0, /*tp_richcompare*/
8029 0, /*tp_weaklistoffset*/
8030 0, /*tp_iter*/
8031 0, /*tp_iternext*/
8032 encoding_map_methods, /*tp_methods*/
8033 0, /*tp_members*/
8034 0, /*tp_getset*/
8035 0, /*tp_base*/
8036 0, /*tp_dict*/
8037 0, /*tp_descr_get*/
8038 0, /*tp_descr_set*/
8039 0, /*tp_dictoffset*/
8040 0, /*tp_init*/
8041 0, /*tp_alloc*/
8042 0, /*tp_new*/
8043 0, /*tp_free*/
8044 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045};
8046
8047PyObject*
8048PyUnicode_BuildEncodingMap(PyObject* string)
8049{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 PyObject *result;
8051 struct encoding_map *mresult;
8052 int i;
8053 int need_dict = 0;
8054 unsigned char level1[32];
8055 unsigned char level2[512];
8056 unsigned char *mlevel1, *mlevel2, *mlevel3;
8057 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008058 int kind;
8059 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008060 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008061 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008063 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008064 PyErr_BadArgument();
8065 return NULL;
8066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008067 kind = PyUnicode_KIND(string);
8068 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008069 length = PyUnicode_GET_LENGTH(string);
8070 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008071 memset(level1, 0xFF, sizeof level1);
8072 memset(level2, 0xFF, sizeof level2);
8073
8074 /* If there isn't a one-to-one mapping of NULL to \0,
8075 or if there are non-BMP characters, we need to use
8076 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008077 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008079 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008080 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008081 ch = PyUnicode_READ(kind, data, i);
8082 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083 need_dict = 1;
8084 break;
8085 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008087 /* unmapped character */
8088 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 l1 = ch >> 11;
8090 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091 if (level1[l1] == 0xFF)
8092 level1[l1] = count2++;
8093 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008094 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095 }
8096
8097 if (count2 >= 0xFF || count3 >= 0xFF)
8098 need_dict = 1;
8099
8100 if (need_dict) {
8101 PyObject *result = PyDict_New();
8102 PyObject *key, *value;
8103 if (!result)
8104 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008105 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008107 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 if (!key || !value)
8109 goto failed1;
8110 if (PyDict_SetItem(result, key, value) == -1)
8111 goto failed1;
8112 Py_DECREF(key);
8113 Py_DECREF(value);
8114 }
8115 return result;
8116 failed1:
8117 Py_XDECREF(key);
8118 Py_XDECREF(value);
8119 Py_DECREF(result);
8120 return NULL;
8121 }
8122
8123 /* Create a three-level trie */
8124 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8125 16*count2 + 128*count3 - 1);
8126 if (!result)
8127 return PyErr_NoMemory();
8128 PyObject_Init(result, &EncodingMapType);
8129 mresult = (struct encoding_map*)result;
8130 mresult->count2 = count2;
8131 mresult->count3 = count3;
8132 mlevel1 = mresult->level1;
8133 mlevel2 = mresult->level23;
8134 mlevel3 = mresult->level23 + 16*count2;
8135 memcpy(mlevel1, level1, 32);
8136 memset(mlevel2, 0xFF, 16*count2);
8137 memset(mlevel3, 0, 128*count3);
8138 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008139 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008141 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8142 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 /* unmapped character */
8144 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008145 o1 = ch>>11;
8146 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008147 i2 = 16*mlevel1[o1] + o2;
8148 if (mlevel2[i2] == 0xFF)
8149 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008150 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151 i3 = 128*mlevel2[i2] + o3;
8152 mlevel3[i3] = i;
8153 }
8154 return result;
8155}
8156
8157static int
Victor Stinner22168992011-11-20 17:09:18 +01008158encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008159{
8160 struct encoding_map *map = (struct encoding_map*)mapping;
8161 int l1 = c>>11;
8162 int l2 = (c>>7) & 0xF;
8163 int l3 = c & 0x7F;
8164 int i;
8165
Victor Stinner22168992011-11-20 17:09:18 +01008166 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008168 if (c == 0)
8169 return 0;
8170 /* level 1*/
8171 i = map->level1[l1];
8172 if (i == 0xFF) {
8173 return -1;
8174 }
8175 /* level 2*/
8176 i = map->level23[16*i+l2];
8177 if (i == 0xFF) {
8178 return -1;
8179 }
8180 /* level 3 */
8181 i = map->level23[16*map->count2 + 128*i + l3];
8182 if (i == 0) {
8183 return -1;
8184 }
8185 return i;
8186}
8187
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008188/* Lookup the character ch in the mapping. If the character
8189 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008190 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008191static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008192charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193{
Christian Heimes217cfd12007-12-02 14:31:20 +00008194 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195 PyObject *x;
8196
8197 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 x = PyObject_GetItem(mapping, w);
8200 Py_DECREF(w);
8201 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8203 /* No mapping found means: mapping is undefined. */
8204 PyErr_Clear();
8205 x = Py_None;
8206 Py_INCREF(x);
8207 return x;
8208 } else
8209 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008211 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008213 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 long value = PyLong_AS_LONG(x);
8215 if (value < 0 || value > 255) {
8216 PyErr_SetString(PyExc_TypeError,
8217 "character mapping must be in range(256)");
8218 Py_DECREF(x);
8219 return NULL;
8220 }
8221 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008222 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008223 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008225 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 /* wrong return value */
8227 PyErr_Format(PyExc_TypeError,
8228 "character mapping must return integer, bytes or None, not %.400s",
8229 x->ob_type->tp_name);
8230 Py_DECREF(x);
8231 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008232 }
8233}
8234
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008235static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008236charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008237{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8239 /* exponentially overallocate to minimize reallocations */
8240 if (requiredsize < 2*outsize)
8241 requiredsize = 2*outsize;
8242 if (_PyBytes_Resize(outobj, requiredsize))
8243 return -1;
8244 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008245}
8246
Benjamin Peterson14339b62009-01-31 16:36:08 +00008247typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008249} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008250/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008251 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 space is available. Return a new reference to the object that
8253 was put in the output buffer, or Py_None, if the mapping was undefined
8254 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008255 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008256static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008257charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008258 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008260 PyObject *rep;
8261 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008262 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008263
Christian Heimes90aa7642007-12-19 02:45:37 +00008264 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008265 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008267 if (res == -1)
8268 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 if (outsize<requiredsize)
8270 if (charmapencode_resize(outobj, outpos, requiredsize))
8271 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008272 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 outstart[(*outpos)++] = (char)res;
8274 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008275 }
8276
8277 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 Py_DECREF(rep);
8282 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008283 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 if (PyLong_Check(rep)) {
8285 Py_ssize_t requiredsize = *outpos+1;
8286 if (outsize<requiredsize)
8287 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8288 Py_DECREF(rep);
8289 return enc_EXCEPTION;
8290 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008291 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008293 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 else {
8295 const char *repchars = PyBytes_AS_STRING(rep);
8296 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8297 Py_ssize_t requiredsize = *outpos+repsize;
8298 if (outsize<requiredsize)
8299 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8300 Py_DECREF(rep);
8301 return enc_EXCEPTION;
8302 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008303 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 memcpy(outstart + *outpos, repchars, repsize);
8305 *outpos += repsize;
8306 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008308 Py_DECREF(rep);
8309 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310}
8311
8312/* handle an error in PyUnicode_EncodeCharmap
8313 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008314static int
8315charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008316 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008318 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008319 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320{
8321 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008323 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008324 enum PyUnicode_Kind kind;
8325 void *data;
8326 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008328 Py_ssize_t collstartpos = *inpos;
8329 Py_ssize_t collendpos = *inpos+1;
8330 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 char *encoding = "charmap";
8332 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008333 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008334 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008335 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336
Benjamin Petersonbac79492012-01-14 13:34:47 -05008337 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008338 return -1;
8339 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008340 /* find all unencodable characters */
8341 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008342 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008343 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008344 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008345 val = encoding_map_lookup(ch, mapping);
8346 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 break;
8348 ++collendpos;
8349 continue;
8350 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008351
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008352 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8353 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 if (rep==NULL)
8355 return -1;
8356 else if (rep!=Py_None) {
8357 Py_DECREF(rep);
8358 break;
8359 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008360 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 }
8363 /* cache callback name lookup
8364 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008365 if (*error_handler == _Py_ERROR_UNKNOWN)
8366 *error_handler = get_error_handler(errors);
8367
8368 switch (*error_handler) {
8369 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008370 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008371 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008372
8373 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008374 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 x = charmapencode_output('?', mapping, res, respos);
8376 if (x==enc_EXCEPTION) {
8377 return -1;
8378 }
8379 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008380 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 return -1;
8382 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008383 }
8384 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008385 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 *inpos = collendpos;
8387 break;
Victor Stinner50149202015-09-22 00:26:54 +02008388
8389 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008390 /* generate replacement (temporarily (mis)uses p) */
8391 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 char buffer[2+29+1+1];
8393 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008394 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 for (cp = buffer; *cp; ++cp) {
8396 x = charmapencode_output(*cp, mapping, res, respos);
8397 if (x==enc_EXCEPTION)
8398 return -1;
8399 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008400 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 return -1;
8402 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008403 }
8404 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008405 *inpos = collendpos;
8406 break;
Victor Stinner50149202015-09-22 00:26:54 +02008407
Benjamin Peterson14339b62009-01-31 16:36:08 +00008408 default:
Victor Stinner50149202015-09-22 00:26:54 +02008409 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008410 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008412 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008414 if (PyBytes_Check(repunicode)) {
8415 /* Directly copy bytes result to output. */
8416 Py_ssize_t outsize = PyBytes_Size(*res);
8417 Py_ssize_t requiredsize;
8418 repsize = PyBytes_Size(repunicode);
8419 requiredsize = *respos + repsize;
8420 if (requiredsize > outsize)
8421 /* Make room for all additional bytes. */
8422 if (charmapencode_resize(res, respos, requiredsize)) {
8423 Py_DECREF(repunicode);
8424 return -1;
8425 }
8426 memcpy(PyBytes_AsString(*res) + *respos,
8427 PyBytes_AsString(repunicode), repsize);
8428 *respos += repsize;
8429 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008430 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008431 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008432 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008433 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008434 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008435 Py_DECREF(repunicode);
8436 return -1;
8437 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008438 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008439 data = PyUnicode_DATA(repunicode);
8440 kind = PyUnicode_KIND(repunicode);
8441 for (index = 0; index < repsize; index++) {
8442 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8443 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008445 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 return -1;
8447 }
8448 else if (x==enc_FAILED) {
8449 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008450 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 return -1;
8452 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008453 }
8454 *inpos = newpos;
8455 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456 }
8457 return 0;
8458}
8459
Alexander Belopolsky40018472011-02-26 01:02:56 +00008460PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008461_PyUnicode_EncodeCharmap(PyObject *unicode,
8462 PyObject *mapping,
8463 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008464{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 /* output object */
8466 PyObject *res = NULL;
8467 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008468 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008469 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008471 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008472 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008474 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008475 void *data;
8476 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008477
Benjamin Petersonbac79492012-01-14 13:34:47 -05008478 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008479 return NULL;
8480 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008481 data = PyUnicode_DATA(unicode);
8482 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008483
Guido van Rossumd57fd912000-03-10 22:53:23 +00008484 /* Default to Latin-1 */
8485 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008486 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008487
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 /* allocate enough for a simple encoding without
8489 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008490 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008491 if (res == NULL)
8492 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008493 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008497 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008499 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 if (x==enc_EXCEPTION) /* error */
8501 goto onError;
8502 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008503 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008505 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 &res, &respos)) {
8507 goto onError;
8508 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008509 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 else
8511 /* done with this character => adjust input position */
8512 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008516 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008517 if (_PyBytes_Resize(&res, respos) < 0)
8518 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008519
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008521 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 return res;
8523
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 Py_XDECREF(res);
8526 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008527 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528 return NULL;
8529}
8530
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531/* Deprecated */
8532PyObject *
8533PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8534 Py_ssize_t size,
8535 PyObject *mapping,
8536 const char *errors)
8537{
8538 PyObject *result;
8539 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8540 if (unicode == NULL)
8541 return NULL;
8542 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8543 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008544 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008545}
8546
Alexander Belopolsky40018472011-02-26 01:02:56 +00008547PyObject *
8548PyUnicode_AsCharmapString(PyObject *unicode,
8549 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008550{
8551 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 PyErr_BadArgument();
8553 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008554 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008555 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008556}
8557
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008559static void
8560make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008561 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008562 Py_ssize_t startpos, Py_ssize_t endpos,
8563 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 *exceptionObject = _PyUnicodeTranslateError_Create(
8567 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008568 }
8569 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8571 goto onError;
8572 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8573 goto onError;
8574 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8575 goto onError;
8576 return;
8577 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008578 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579 }
8580}
8581
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008582/* error handling callback helper:
8583 build arguments, call the callback and check the arguments,
8584 put the result into newpos and return the replacement string, which
8585 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008586static PyObject *
8587unicode_translate_call_errorhandler(const char *errors,
8588 PyObject **errorHandler,
8589 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008591 Py_ssize_t startpos, Py_ssize_t endpos,
8592 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008594 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008595
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008596 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 PyObject *restuple;
8598 PyObject *resunicode;
8599
8600 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008601 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008604 }
8605
8606 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610
8611 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008615 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008616 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 Py_DECREF(restuple);
8618 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008619 }
8620 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 &resunicode, &i_newpos)) {
8622 Py_DECREF(restuple);
8623 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008625 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008627 else
8628 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008630 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 Py_DECREF(restuple);
8632 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008633 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634 Py_INCREF(resunicode);
8635 Py_DECREF(restuple);
8636 return resunicode;
8637}
8638
8639/* Lookup the character ch in the mapping and put the result in result,
8640 which must be decrefed by the caller.
8641 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008642static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644{
Christian Heimes217cfd12007-12-02 14:31:20 +00008645 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646 PyObject *x;
8647
8648 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 x = PyObject_GetItem(mapping, w);
8651 Py_DECREF(w);
8652 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8654 /* No mapping found means: use 1:1 mapping. */
8655 PyErr_Clear();
8656 *result = NULL;
8657 return 0;
8658 } else
8659 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 }
8661 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 *result = x;
8663 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008665 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008667 if (value < 0 || value > MAX_UNICODE) {
8668 PyErr_Format(PyExc_ValueError,
8669 "character mapping must be in range(0x%x)",
8670 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 Py_DECREF(x);
8672 return -1;
8673 }
8674 *result = x;
8675 return 0;
8676 }
8677 else if (PyUnicode_Check(x)) {
8678 *result = x;
8679 return 0;
8680 }
8681 else {
8682 /* wrong return value */
8683 PyErr_SetString(PyExc_TypeError,
8684 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008685 Py_DECREF(x);
8686 return -1;
8687 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688}
Victor Stinner1194ea02014-04-04 19:37:40 +02008689
8690/* lookup the character, write the result into the writer.
8691 Return 1 if the result was written into the writer, return 0 if the mapping
8692 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008693static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008694charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8695 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696{
Victor Stinner1194ea02014-04-04 19:37:40 +02008697 PyObject *item;
8698
8699 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008701
8702 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008704 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008705 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008707 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008708 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008709
8710 if (item == Py_None) {
8711 Py_DECREF(item);
8712 return 0;
8713 }
8714
8715 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008716 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8717 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8718 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008719 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8720 Py_DECREF(item);
8721 return -1;
8722 }
8723 Py_DECREF(item);
8724 return 1;
8725 }
8726
8727 if (!PyUnicode_Check(item)) {
8728 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008730 }
8731
8732 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8733 Py_DECREF(item);
8734 return -1;
8735 }
8736
8737 Py_DECREF(item);
8738 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008739}
8740
Victor Stinner89a76ab2014-04-05 11:44:04 +02008741static int
8742unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8743 Py_UCS1 *translate)
8744{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008745 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008746 int ret = 0;
8747
Victor Stinner89a76ab2014-04-05 11:44:04 +02008748 if (charmaptranslate_lookup(ch, mapping, &item)) {
8749 return -1;
8750 }
8751
8752 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008753 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008754 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008755 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008756 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008757 /* not found => default to 1:1 mapping */
8758 translate[ch] = ch;
8759 return 1;
8760 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008761 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008762 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008763 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8764 used it */
8765 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008766 /* invalid character or character outside ASCII:
8767 skip the fast translate */
8768 goto exit;
8769 }
8770 translate[ch] = (Py_UCS1)replace;
8771 }
8772 else if (PyUnicode_Check(item)) {
8773 Py_UCS4 replace;
8774
8775 if (PyUnicode_READY(item) == -1) {
8776 Py_DECREF(item);
8777 return -1;
8778 }
8779 if (PyUnicode_GET_LENGTH(item) != 1)
8780 goto exit;
8781
8782 replace = PyUnicode_READ_CHAR(item, 0);
8783 if (replace > 127)
8784 goto exit;
8785 translate[ch] = (Py_UCS1)replace;
8786 }
8787 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008788 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008789 goto exit;
8790 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008791 ret = 1;
8792
Benjamin Peterson1365de72014-04-07 20:15:41 -04008793 exit:
8794 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008795 return ret;
8796}
8797
8798/* Fast path for ascii => ascii translation. Return 1 if the whole string
8799 was translated into writer, return 0 if the input string was partially
8800 translated into writer, raise an exception and return -1 on error. */
8801static int
8802unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008803 _PyUnicodeWriter *writer, int ignore,
8804 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008805{
Victor Stinner872b2912014-04-05 14:27:07 +02008806 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008807 Py_ssize_t len;
8808 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008809 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008810
Victor Stinner89a76ab2014-04-05 11:44:04 +02008811 len = PyUnicode_GET_LENGTH(input);
8812
Victor Stinner872b2912014-04-05 14:27:07 +02008813 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008814
8815 in = PyUnicode_1BYTE_DATA(input);
8816 end = in + len;
8817
8818 assert(PyUnicode_IS_ASCII(writer->buffer));
8819 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8820 out = PyUnicode_1BYTE_DATA(writer->buffer);
8821
Victor Stinner872b2912014-04-05 14:27:07 +02008822 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008823 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008824 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008825 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008826 int translate = unicode_fast_translate_lookup(mapping, ch,
8827 ascii_table);
8828 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008829 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008830 if (translate == 0)
8831 goto exit;
8832 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008833 }
Victor Stinner872b2912014-04-05 14:27:07 +02008834 if (ch2 == 0xfe) {
8835 if (ignore)
8836 continue;
8837 goto exit;
8838 }
8839 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008841 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008842 }
Victor Stinner872b2912014-04-05 14:27:07 +02008843 res = 1;
8844
8845exit:
8846 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008847 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008848 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008849}
8850
Victor Stinner3222da22015-10-01 22:07:32 +02008851static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008852_PyUnicode_TranslateCharmap(PyObject *input,
8853 PyObject *mapping,
8854 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008855{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008856 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008857 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008858 Py_ssize_t size, i;
8859 int kind;
8860 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008861 _PyUnicodeWriter writer;
8862 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008863 char *reason = "character maps to <undefined>";
8864 PyObject *errorHandler = NULL;
8865 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008866 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008867 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008868
Guido van Rossumd57fd912000-03-10 22:53:23 +00008869 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008870 PyErr_BadArgument();
8871 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008872 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874 if (PyUnicode_READY(input) == -1)
8875 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008876 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 kind = PyUnicode_KIND(input);
8878 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008879
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008880 if (size == 0)
8881 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008883 /* allocate enough for a simple 1:1 translation without
8884 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008885 _PyUnicodeWriter_Init(&writer);
8886 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008887 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008888
Victor Stinner872b2912014-04-05 14:27:07 +02008889 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8890
Victor Stinner33798672016-03-01 21:59:58 +01008891 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008892 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008893 if (PyUnicode_IS_ASCII(input)) {
8894 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8895 if (res < 0) {
8896 _PyUnicodeWriter_Dealloc(&writer);
8897 return NULL;
8898 }
8899 if (res == 1)
8900 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901 }
Victor Stinner33798672016-03-01 21:59:58 +01008902 else {
8903 i = 0;
8904 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008907 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008908 int translate;
8909 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8910 Py_ssize_t newpos;
8911 /* startpos for collecting untranslatable chars */
8912 Py_ssize_t collstart;
8913 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008914 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008915
Victor Stinner1194ea02014-04-04 19:37:40 +02008916 ch = PyUnicode_READ(kind, data, i);
8917 translate = charmaptranslate_output(ch, mapping, &writer);
8918 if (translate < 0)
8919 goto onError;
8920
8921 if (translate != 0) {
8922 /* it worked => adjust input pointer */
8923 ++i;
8924 continue;
8925 }
8926
8927 /* untranslatable character */
8928 collstart = i;
8929 collend = i+1;
8930
8931 /* find all untranslatable characters */
8932 while (collend < size) {
8933 PyObject *x;
8934 ch = PyUnicode_READ(kind, data, collend);
8935 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008936 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008937 Py_XDECREF(x);
8938 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008940 ++collend;
8941 }
8942
8943 if (ignore) {
8944 i = collend;
8945 }
8946 else {
8947 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8948 reason, input, &exc,
8949 collstart, collend, &newpos);
8950 if (repunicode == NULL)
8951 goto onError;
8952 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008953 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008954 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008955 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008956 Py_DECREF(repunicode);
8957 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008958 }
8959 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008960 Py_XDECREF(exc);
8961 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008962 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008963
Benjamin Peterson29060642009-01-31 22:14:21 +00008964 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008965 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008966 Py_XDECREF(exc);
8967 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008968 return NULL;
8969}
8970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971/* Deprecated. Use PyUnicode_Translate instead. */
8972PyObject *
8973PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8974 Py_ssize_t size,
8975 PyObject *mapping,
8976 const char *errors)
8977{
Christian Heimes5f520f42012-09-11 14:03:25 +02008978 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8980 if (!unicode)
8981 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008982 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8983 Py_DECREF(unicode);
8984 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008985}
8986
Alexander Belopolsky40018472011-02-26 01:02:56 +00008987PyObject *
8988PyUnicode_Translate(PyObject *str,
8989 PyObject *mapping,
8990 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008991{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008992 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02008993 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008994 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008995}
Tim Petersced69f82003-09-16 20:30:58 +00008996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008998fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008999{
9000 /* No need to call PyUnicode_READY(self) because this function is only
9001 called as a callback from fixup() which does it already. */
9002 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9003 const int kind = PyUnicode_KIND(self);
9004 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009005 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009006 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 Py_ssize_t i;
9008
9009 for (i = 0; i < len; ++i) {
9010 ch = PyUnicode_READ(kind, data, i);
9011 fixed = 0;
9012 if (ch > 127) {
9013 if (Py_UNICODE_ISSPACE(ch))
9014 fixed = ' ';
9015 else {
9016 const int decimal = Py_UNICODE_TODECIMAL(ch);
9017 if (decimal >= 0)
9018 fixed = '0' + decimal;
9019 }
9020 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009021 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009022 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009023 PyUnicode_WRITE(kind, data, i, fixed);
9024 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009025 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009026 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028 }
9029
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009030 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031}
9032
9033PyObject *
9034_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9035{
9036 if (!PyUnicode_Check(unicode)) {
9037 PyErr_BadInternalCall();
9038 return NULL;
9039 }
9040 if (PyUnicode_READY(unicode) == -1)
9041 return NULL;
9042 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9043 /* If the string is already ASCII, just return the same string */
9044 Py_INCREF(unicode);
9045 return unicode;
9046 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009047 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009048}
9049
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009050PyObject *
9051PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9052 Py_ssize_t length)
9053{
Victor Stinnerf0124502011-11-21 23:12:56 +01009054 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009055 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009056 Py_UCS4 maxchar;
9057 enum PyUnicode_Kind kind;
9058 void *data;
9059
Victor Stinner99d7ad02012-02-22 13:37:39 +01009060 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009061 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009062 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009063 if (ch > 127) {
9064 int decimal = Py_UNICODE_TODECIMAL(ch);
9065 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009066 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009067 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009068 }
9069 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009070
9071 /* Copy to a new string */
9072 decimal = PyUnicode_New(length, maxchar);
9073 if (decimal == NULL)
9074 return decimal;
9075 kind = PyUnicode_KIND(decimal);
9076 data = PyUnicode_DATA(decimal);
9077 /* Iterate over code points */
9078 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009079 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009080 if (ch > 127) {
9081 int decimal = Py_UNICODE_TODECIMAL(ch);
9082 if (decimal >= 0)
9083 ch = '0' + decimal;
9084 }
9085 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009087 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009088}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009089/* --- Decimal Encoder ---------------------------------------------------- */
9090
Alexander Belopolsky40018472011-02-26 01:02:56 +00009091int
9092PyUnicode_EncodeDecimal(Py_UNICODE *s,
9093 Py_ssize_t length,
9094 char *output,
9095 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009096{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009097 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009098 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009099 enum PyUnicode_Kind kind;
9100 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009101
9102 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009103 PyErr_BadArgument();
9104 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009105 }
9106
Victor Stinner42bf7752011-11-21 22:52:58 +01009107 unicode = PyUnicode_FromUnicode(s, length);
9108 if (unicode == NULL)
9109 return -1;
9110
Benjamin Petersonbac79492012-01-14 13:34:47 -05009111 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009112 Py_DECREF(unicode);
9113 return -1;
9114 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009115 kind = PyUnicode_KIND(unicode);
9116 data = PyUnicode_DATA(unicode);
9117
Victor Stinnerb84d7232011-11-22 01:50:07 +01009118 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009119 PyObject *exc;
9120 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009121 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009122 Py_ssize_t startpos;
9123
9124 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009125
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009127 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009128 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009129 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009130 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009131 decimal = Py_UNICODE_TODECIMAL(ch);
9132 if (decimal >= 0) {
9133 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009134 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009135 continue;
9136 }
9137 if (0 < ch && ch < 256) {
9138 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009139 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 continue;
9141 }
Victor Stinner6345be92011-11-25 20:09:01 +01009142
Victor Stinner42bf7752011-11-21 22:52:58 +01009143 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009144 exc = NULL;
9145 raise_encode_exception(&exc, "decimal", unicode,
9146 startpos, startpos+1,
9147 "invalid decimal Unicode string");
9148 Py_XDECREF(exc);
9149 Py_DECREF(unicode);
9150 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009151 }
9152 /* 0-terminate the output string */
9153 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009154 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009155 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009156}
9157
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158/* --- Helpers ------------------------------------------------------------ */
9159
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009160/* helper macro to fixup start/end slice values */
9161#define ADJUST_INDICES(start, end, len) \
9162 if (end > len) \
9163 end = len; \
9164 else if (end < 0) { \
9165 end += len; \
9166 if (end < 0) \
9167 end = 0; \
9168 } \
9169 if (start < 0) { \
9170 start += len; \
9171 if (start < 0) \
9172 start = 0; \
9173 }
9174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009176any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009178 Py_ssize_t end,
9179 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009181 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 void *buf1, *buf2;
9183 Py_ssize_t len1, len2, result;
9184
9185 kind1 = PyUnicode_KIND(s1);
9186 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009187 if (kind1 < kind2)
9188 return -1;
9189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 len1 = PyUnicode_GET_LENGTH(s1);
9191 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009192 ADJUST_INDICES(start, end, len1);
9193 if (end - start < len2)
9194 return -1;
9195
9196 buf1 = PyUnicode_DATA(s1);
9197 buf2 = PyUnicode_DATA(s2);
9198 if (len2 == 1) {
9199 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9200 result = findchar((const char *)buf1 + kind1*start,
9201 kind1, end - start, ch, direction);
9202 if (result == -1)
9203 return -1;
9204 else
9205 return start + result;
9206 }
9207
9208 if (kind2 != kind1) {
9209 buf2 = _PyUnicode_AsKind(s2, kind1);
9210 if (!buf2)
9211 return -2;
9212 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213
Victor Stinner794d5672011-10-10 03:21:36 +02009214 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009215 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009216 case PyUnicode_1BYTE_KIND:
9217 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9218 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9219 else
9220 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9221 break;
9222 case PyUnicode_2BYTE_KIND:
9223 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9224 break;
9225 case PyUnicode_4BYTE_KIND:
9226 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9227 break;
9228 default:
9229 assert(0); result = -2;
9230 }
9231 }
9232 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009233 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009234 case PyUnicode_1BYTE_KIND:
9235 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9236 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9237 else
9238 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9239 break;
9240 case PyUnicode_2BYTE_KIND:
9241 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9242 break;
9243 case PyUnicode_4BYTE_KIND:
9244 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9245 break;
9246 default:
9247 assert(0); result = -2;
9248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249 }
9250
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009251 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 PyMem_Free(buf2);
9253
9254 return result;
9255}
9256
9257Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009258_PyUnicode_InsertThousandsGrouping(
9259 PyObject *unicode, Py_ssize_t index,
9260 Py_ssize_t n_buffer,
9261 void *digits, Py_ssize_t n_digits,
9262 Py_ssize_t min_width,
9263 const char *grouping, PyObject *thousands_sep,
9264 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265{
Victor Stinner41a863c2012-02-24 00:37:51 +01009266 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009267 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009268 Py_ssize_t thousands_sep_len;
9269 Py_ssize_t len;
9270
9271 if (unicode != NULL) {
9272 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009273 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009274 }
9275 else {
9276 kind = PyUnicode_1BYTE_KIND;
9277 data = NULL;
9278 }
9279 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9280 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9281 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9282 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009283 if (thousands_sep_kind < kind) {
9284 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9285 if (!thousands_sep_data)
9286 return -1;
9287 }
9288 else {
9289 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9290 if (!data)
9291 return -1;
9292 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009293 }
9294
Benjamin Petersonead6b532011-12-20 17:23:42 -06009295 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009297 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009299 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009300 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009301 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009302 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009303 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009304 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009305 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009306 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009307 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009309 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009310 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009311 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009312 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009313 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009314 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009315 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009316 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009317 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009318 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009319 break;
9320 default:
9321 assert(0);
9322 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009324 if (unicode != NULL && thousands_sep_kind != kind) {
9325 if (thousands_sep_kind < kind)
9326 PyMem_Free(thousands_sep_data);
9327 else
9328 PyMem_Free(data);
9329 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009330 if (unicode == NULL) {
9331 *maxchar = 127;
9332 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009333 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009334 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 }
9336 }
9337 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338}
9339
9340
Alexander Belopolsky40018472011-02-26 01:02:56 +00009341Py_ssize_t
9342PyUnicode_Count(PyObject *str,
9343 PyObject *substr,
9344 Py_ssize_t start,
9345 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009347 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009348 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 void *buf1 = NULL, *buf2 = NULL;
9350 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009351
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009352 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009353 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009354
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009355 kind1 = PyUnicode_KIND(str);
9356 kind2 = PyUnicode_KIND(substr);
9357 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009358 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009359
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009360 len1 = PyUnicode_GET_LENGTH(str);
9361 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009363 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009364 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009365
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009366 buf1 = PyUnicode_DATA(str);
9367 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009368 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009369 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009370 if (!buf2)
9371 goto onError;
9372 }
9373
9374 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009376 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009377 result = asciilib_count(
9378 ((Py_UCS1*)buf1) + start, end - start,
9379 buf2, len2, PY_SSIZE_T_MAX
9380 );
9381 else
9382 result = ucs1lib_count(
9383 ((Py_UCS1*)buf1) + start, end - start,
9384 buf2, len2, PY_SSIZE_T_MAX
9385 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 break;
9387 case PyUnicode_2BYTE_KIND:
9388 result = ucs2lib_count(
9389 ((Py_UCS2*)buf1) + start, end - start,
9390 buf2, len2, PY_SSIZE_T_MAX
9391 );
9392 break;
9393 case PyUnicode_4BYTE_KIND:
9394 result = ucs4lib_count(
9395 ((Py_UCS4*)buf1) + start, end - start,
9396 buf2, len2, PY_SSIZE_T_MAX
9397 );
9398 break;
9399 default:
9400 assert(0); result = 0;
9401 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009402
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009403 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404 PyMem_Free(buf2);
9405
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009408 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 PyMem_Free(buf2);
9410 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411}
9412
Alexander Belopolsky40018472011-02-26 01:02:56 +00009413Py_ssize_t
9414PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009415 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009416 Py_ssize_t start,
9417 Py_ssize_t end,
9418 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009419{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009420 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009421 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009422
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009423 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424}
9425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426Py_ssize_t
9427PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9428 Py_ssize_t start, Py_ssize_t end,
9429 int direction)
9430{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009432 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009433 if (PyUnicode_READY(str) == -1)
9434 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009435 if (start < 0 || end < 0) {
9436 PyErr_SetString(PyExc_IndexError, "string index out of range");
9437 return -2;
9438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 if (end > PyUnicode_GET_LENGTH(str))
9440 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009441 if (start >= end)
9442 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009444 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9445 kind, end-start, ch, direction);
9446 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009448 else
9449 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450}
9451
Alexander Belopolsky40018472011-02-26 01:02:56 +00009452static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009453tailmatch(PyObject *self,
9454 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009455 Py_ssize_t start,
9456 Py_ssize_t end,
9457 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 int kind_self;
9460 int kind_sub;
9461 void *data_self;
9462 void *data_sub;
9463 Py_ssize_t offset;
9464 Py_ssize_t i;
9465 Py_ssize_t end_sub;
9466
9467 if (PyUnicode_READY(self) == -1 ||
9468 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009469 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9472 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009475
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009476 if (PyUnicode_GET_LENGTH(substring) == 0)
9477 return 1;
9478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 kind_self = PyUnicode_KIND(self);
9480 data_self = PyUnicode_DATA(self);
9481 kind_sub = PyUnicode_KIND(substring);
9482 data_sub = PyUnicode_DATA(substring);
9483 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9484
9485 if (direction > 0)
9486 offset = end;
9487 else
9488 offset = start;
9489
9490 if (PyUnicode_READ(kind_self, data_self, offset) ==
9491 PyUnicode_READ(kind_sub, data_sub, 0) &&
9492 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9493 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9494 /* If both are of the same kind, memcmp is sufficient */
9495 if (kind_self == kind_sub) {
9496 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009497 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 data_sub,
9499 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009500 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009502 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 else {
9504 /* We do not need to compare 0 and len(substring)-1 because
9505 the if statement above ensured already that they are equal
9506 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507 for (i = 1; i < end_sub; ++i) {
9508 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9509 PyUnicode_READ(kind_sub, data_sub, i))
9510 return 0;
9511 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009512 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009513 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514 }
9515
9516 return 0;
9517}
9518
Alexander Belopolsky40018472011-02-26 01:02:56 +00009519Py_ssize_t
9520PyUnicode_Tailmatch(PyObject *str,
9521 PyObject *substr,
9522 Py_ssize_t start,
9523 Py_ssize_t end,
9524 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009525{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009526 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009527 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009528
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009529 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530}
9531
Guido van Rossumd57fd912000-03-10 22:53:23 +00009532/* Apply fixfct filter to the Unicode object self and return a
9533 reference to the modified object */
9534
Alexander Belopolsky40018472011-02-26 01:02:56 +00009535static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009536fixup(PyObject *self,
9537 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009538{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009539 PyObject *u;
9540 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009541 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009543 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009546 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548 /* fix functions return the new maximum character in a string,
9549 if the kind of the resulting unicode object does not change,
9550 everything is fine. Otherwise we need to change the string kind
9551 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009552 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009553
9554 if (maxchar_new == 0) {
9555 /* no changes */;
9556 if (PyUnicode_CheckExact(self)) {
9557 Py_DECREF(u);
9558 Py_INCREF(self);
9559 return self;
9560 }
9561 else
9562 return u;
9563 }
9564
Victor Stinnere6abb482012-05-02 01:15:40 +02009565 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566
Victor Stinnereaab6042011-12-11 22:22:39 +01009567 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009569
9570 /* In case the maximum character changed, we need to
9571 convert the string to the new category. */
9572 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9573 if (v == NULL) {
9574 Py_DECREF(u);
9575 return NULL;
9576 }
9577 if (maxchar_new > maxchar_old) {
9578 /* If the maxchar increased so that the kind changed, not all
9579 characters are representable anymore and we need to fix the
9580 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009581 _PyUnicode_FastCopyCharacters(v, 0,
9582 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009583 maxchar_old = fixfct(v);
9584 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 }
9586 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009587 _PyUnicode_FastCopyCharacters(v, 0,
9588 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009590 Py_DECREF(u);
9591 assert(_PyUnicode_CheckConsistency(v, 1));
9592 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593}
9594
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009595static PyObject *
9596ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009597{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009598 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9599 char *resdata, *data = PyUnicode_DATA(self);
9600 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009601
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009602 res = PyUnicode_New(len, 127);
9603 if (res == NULL)
9604 return NULL;
9605 resdata = PyUnicode_DATA(res);
9606 if (lower)
9607 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009609 _Py_bytes_upper(resdata, data, len);
9610 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009611}
9612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009614handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009616 Py_ssize_t j;
9617 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009618 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009619 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009620
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9622
9623 where ! is a negation and \p{xxx} is a character with property xxx.
9624 */
9625 for (j = i - 1; j >= 0; j--) {
9626 c = PyUnicode_READ(kind, data, j);
9627 if (!_PyUnicode_IsCaseIgnorable(c))
9628 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9631 if (final_sigma) {
9632 for (j = i + 1; j < length; j++) {
9633 c = PyUnicode_READ(kind, data, j);
9634 if (!_PyUnicode_IsCaseIgnorable(c))
9635 break;
9636 }
9637 final_sigma = j == length || !_PyUnicode_IsCased(c);
9638 }
9639 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009640}
9641
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009642static int
9643lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9644 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009646 /* Obscure special case. */
9647 if (c == 0x3A3) {
9648 mapped[0] = handle_capital_sigma(kind, data, length, i);
9649 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009651 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652}
9653
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009654static Py_ssize_t
9655do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009657 Py_ssize_t i, k = 0;
9658 int n_res, j;
9659 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009660
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661 c = PyUnicode_READ(kind, data, 0);
9662 n_res = _PyUnicode_ToUpperFull(c, mapped);
9663 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009664 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009665 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009666 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667 for (i = 1; i < length; i++) {
9668 c = PyUnicode_READ(kind, data, i);
9669 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9670 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009671 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009672 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009673 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009674 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009675 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676}
9677
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009678static Py_ssize_t
9679do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9680 Py_ssize_t i, k = 0;
9681
9682 for (i = 0; i < length; i++) {
9683 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9684 int n_res, j;
9685 if (Py_UNICODE_ISUPPER(c)) {
9686 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9687 }
9688 else if (Py_UNICODE_ISLOWER(c)) {
9689 n_res = _PyUnicode_ToUpperFull(c, mapped);
9690 }
9691 else {
9692 n_res = 1;
9693 mapped[0] = c;
9694 }
9695 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009696 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009697 res[k++] = mapped[j];
9698 }
9699 }
9700 return k;
9701}
9702
9703static Py_ssize_t
9704do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9705 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009707 Py_ssize_t i, k = 0;
9708
9709 for (i = 0; i < length; i++) {
9710 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9711 int n_res, j;
9712 if (lower)
9713 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9714 else
9715 n_res = _PyUnicode_ToUpperFull(c, mapped);
9716 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009717 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009718 res[k++] = mapped[j];
9719 }
9720 }
9721 return k;
9722}
9723
9724static Py_ssize_t
9725do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9726{
9727 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9728}
9729
9730static Py_ssize_t
9731do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9732{
9733 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9734}
9735
Benjamin Petersone51757f2012-01-12 21:10:29 -05009736static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009737do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9738{
9739 Py_ssize_t i, k = 0;
9740
9741 for (i = 0; i < length; i++) {
9742 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9743 Py_UCS4 mapped[3];
9744 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9745 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009746 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009747 res[k++] = mapped[j];
9748 }
9749 }
9750 return k;
9751}
9752
9753static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009754do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9755{
9756 Py_ssize_t i, k = 0;
9757 int previous_is_cased;
9758
9759 previous_is_cased = 0;
9760 for (i = 0; i < length; i++) {
9761 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9762 Py_UCS4 mapped[3];
9763 int n_res, j;
9764
9765 if (previous_is_cased)
9766 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9767 else
9768 n_res = _PyUnicode_ToTitleFull(c, mapped);
9769
9770 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009771 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009772 res[k++] = mapped[j];
9773 }
9774
9775 previous_is_cased = _PyUnicode_IsCased(c);
9776 }
9777 return k;
9778}
9779
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009780static PyObject *
9781case_operation(PyObject *self,
9782 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9783{
9784 PyObject *res = NULL;
9785 Py_ssize_t length, newlength = 0;
9786 int kind, outkind;
9787 void *data, *outdata;
9788 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9789
Benjamin Petersoneea48462012-01-16 14:28:50 -05009790 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009791
9792 kind = PyUnicode_KIND(self);
9793 data = PyUnicode_DATA(self);
9794 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009795 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009796 PyErr_SetString(PyExc_OverflowError, "string is too long");
9797 return NULL;
9798 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009799 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009800 if (tmp == NULL)
9801 return PyErr_NoMemory();
9802 newlength = perform(kind, data, length, tmp, &maxchar);
9803 res = PyUnicode_New(newlength, maxchar);
9804 if (res == NULL)
9805 goto leave;
9806 tmpend = tmp + newlength;
9807 outdata = PyUnicode_DATA(res);
9808 outkind = PyUnicode_KIND(res);
9809 switch (outkind) {
9810 case PyUnicode_1BYTE_KIND:
9811 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9812 break;
9813 case PyUnicode_2BYTE_KIND:
9814 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9815 break;
9816 case PyUnicode_4BYTE_KIND:
9817 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9818 break;
9819 default:
9820 assert(0);
9821 break;
9822 }
9823 leave:
9824 PyMem_FREE(tmp);
9825 return res;
9826}
9827
Tim Peters8ce9f162004-08-27 01:49:32 +00009828PyObject *
9829PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009832 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009833 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009834 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009835 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9836 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009837 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009839 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009840 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009841 int use_memcpy;
9842 unsigned char *res_data = NULL, *sep_data = NULL;
9843 PyObject *last_obj;
9844 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009845
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009846 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009847 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009848 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009849 }
9850
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009851 /* NOTE: the following code can't call back into Python code,
9852 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009853 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009854
Tim Peters05eba1f2004-08-27 21:32:02 +00009855 seqlen = PySequence_Fast_GET_SIZE(fseq);
9856 /* If empty sequence, return u"". */
9857 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009858 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009859 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009860 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009861
Tim Peters05eba1f2004-08-27 21:32:02 +00009862 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009863 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009864 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009865 if (seqlen == 1) {
9866 if (PyUnicode_CheckExact(items[0])) {
9867 res = items[0];
9868 Py_INCREF(res);
9869 Py_DECREF(fseq);
9870 return res;
9871 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009872 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009873 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009874 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009875 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009876 /* Set up sep and seplen */
9877 if (separator == NULL) {
9878 /* fall back to a blank space separator */
9879 sep = PyUnicode_FromOrdinal(' ');
9880 if (!sep)
9881 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009882 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009883 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009884 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009885 else {
9886 if (!PyUnicode_Check(separator)) {
9887 PyErr_Format(PyExc_TypeError,
9888 "separator: expected str instance,"
9889 " %.80s found",
9890 Py_TYPE(separator)->tp_name);
9891 goto onError;
9892 }
9893 if (PyUnicode_READY(separator))
9894 goto onError;
9895 sep = separator;
9896 seplen = PyUnicode_GET_LENGTH(separator);
9897 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9898 /* inc refcount to keep this code path symmetric with the
9899 above case of a blank separator */
9900 Py_INCREF(sep);
9901 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009902 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009903 }
9904
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009905 /* There are at least two things to join, or else we have a subclass
9906 * of str in the sequence.
9907 * Do a pre-pass to figure out the total amount of space we'll
9908 * need (sz), and see whether all argument are strings.
9909 */
9910 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009911#ifdef Py_DEBUG
9912 use_memcpy = 0;
9913#else
9914 use_memcpy = 1;
9915#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009916 for (i = 0; i < seqlen; i++) {
9917 const Py_ssize_t old_sz = sz;
9918 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009919 if (!PyUnicode_Check(item)) {
9920 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009921 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009922 " %.80s found",
9923 i, Py_TYPE(item)->tp_name);
9924 goto onError;
9925 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926 if (PyUnicode_READY(item) == -1)
9927 goto onError;
9928 sz += PyUnicode_GET_LENGTH(item);
9929 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009930 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009931 if (i != 0)
9932 sz += seplen;
9933 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9934 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009935 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009936 goto onError;
9937 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009938 if (use_memcpy && last_obj != NULL) {
9939 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9940 use_memcpy = 0;
9941 }
9942 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009943 }
Tim Petersced69f82003-09-16 20:30:58 +00009944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009946 if (res == NULL)
9947 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009948
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009949 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009950#ifdef Py_DEBUG
9951 use_memcpy = 0;
9952#else
9953 if (use_memcpy) {
9954 res_data = PyUnicode_1BYTE_DATA(res);
9955 kind = PyUnicode_KIND(res);
9956 if (seplen != 0)
9957 sep_data = PyUnicode_1BYTE_DATA(sep);
9958 }
9959#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009960 if (use_memcpy) {
9961 for (i = 0; i < seqlen; ++i) {
9962 Py_ssize_t itemlen;
9963 item = items[i];
9964
9965 /* Copy item, and maybe the separator. */
9966 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009967 Py_MEMCPY(res_data,
9968 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009969 kind * seplen);
9970 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009971 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009972
9973 itemlen = PyUnicode_GET_LENGTH(item);
9974 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009975 Py_MEMCPY(res_data,
9976 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009977 kind * itemlen);
9978 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009979 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009980 }
9981 assert(res_data == PyUnicode_1BYTE_DATA(res)
9982 + kind * PyUnicode_GET_LENGTH(res));
9983 }
9984 else {
9985 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9986 Py_ssize_t itemlen;
9987 item = items[i];
9988
9989 /* Copy item, and maybe the separator. */
9990 if (i && seplen != 0) {
9991 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9992 res_offset += seplen;
9993 }
9994
9995 itemlen = PyUnicode_GET_LENGTH(item);
9996 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009997 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009998 res_offset += itemlen;
9999 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010000 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010001 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010002 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010003
Tim Peters05eba1f2004-08-27 21:32:02 +000010004 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010006 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008
Benjamin Peterson29060642009-01-31 22:14:21 +000010009 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +000010010 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010012 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010013 return NULL;
10014}
10015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016#define FILL(kind, data, value, start, length) \
10017 do { \
10018 Py_ssize_t i_ = 0; \
10019 assert(kind != PyUnicode_WCHAR_KIND); \
10020 switch ((kind)) { \
10021 case PyUnicode_1BYTE_KIND: { \
10022 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010023 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024 break; \
10025 } \
10026 case PyUnicode_2BYTE_KIND: { \
10027 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10028 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10029 break; \
10030 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010031 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10033 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10034 break; \
10035 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010036 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 } \
10038 } while (0)
10039
Victor Stinnerd3f08822012-05-29 12:57:52 +020010040void
10041_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10042 Py_UCS4 fill_char)
10043{
10044 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10045 const void *data = PyUnicode_DATA(unicode);
10046 assert(PyUnicode_IS_READY(unicode));
10047 assert(unicode_modifiable(unicode));
10048 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10049 assert(start >= 0);
10050 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10051 FILL(kind, data, fill_char, start, length);
10052}
10053
Victor Stinner3fe55312012-01-04 00:33:50 +010010054Py_ssize_t
10055PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10056 Py_UCS4 fill_char)
10057{
10058 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010059
10060 if (!PyUnicode_Check(unicode)) {
10061 PyErr_BadInternalCall();
10062 return -1;
10063 }
10064 if (PyUnicode_READY(unicode) == -1)
10065 return -1;
10066 if (unicode_check_modifiable(unicode))
10067 return -1;
10068
Victor Stinnerd3f08822012-05-29 12:57:52 +020010069 if (start < 0) {
10070 PyErr_SetString(PyExc_IndexError, "string index out of range");
10071 return -1;
10072 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010073 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10074 PyErr_SetString(PyExc_ValueError,
10075 "fill character is bigger than "
10076 "the string maximum character");
10077 return -1;
10078 }
10079
10080 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10081 length = Py_MIN(maxlen, length);
10082 if (length <= 0)
10083 return 0;
10084
Victor Stinnerd3f08822012-05-29 12:57:52 +020010085 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010086 return length;
10087}
10088
Victor Stinner9310abb2011-10-05 00:59:23 +020010089static PyObject *
10090pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010091 Py_ssize_t left,
10092 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010094{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010095 PyObject *u;
10096 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010097 int kind;
10098 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010099
10100 if (left < 0)
10101 left = 0;
10102 if (right < 0)
10103 right = 0;
10104
Victor Stinnerc4b49542011-12-11 22:44:26 +010010105 if (left == 0 && right == 0)
10106 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10109 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010110 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10111 return NULL;
10112 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010114 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010116 if (!u)
10117 return NULL;
10118
10119 kind = PyUnicode_KIND(u);
10120 data = PyUnicode_DATA(u);
10121 if (left)
10122 FILL(kind, data, fill, 0, left);
10123 if (right)
10124 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010125 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010126 assert(_PyUnicode_CheckConsistency(u, 1));
10127 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128}
10129
Alexander Belopolsky40018472011-02-26 01:02:56 +000010130PyObject *
10131PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010135 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010137
Benjamin Petersonead6b532011-12-20 17:23:42 -060010138 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010140 if (PyUnicode_IS_ASCII(string))
10141 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010143 PyUnicode_GET_LENGTH(string), keepends);
10144 else
10145 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010146 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 break;
10149 case PyUnicode_2BYTE_KIND:
10150 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010151 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 PyUnicode_GET_LENGTH(string), keepends);
10153 break;
10154 case PyUnicode_4BYTE_KIND:
10155 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010156 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 PyUnicode_GET_LENGTH(string), keepends);
10158 break;
10159 default:
10160 assert(0);
10161 list = 0;
10162 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010163 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010164}
10165
Alexander Belopolsky40018472011-02-26 01:02:56 +000010166static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010167split(PyObject *self,
10168 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010169 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010171 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 void *buf1, *buf2;
10173 Py_ssize_t len1, len2;
10174 PyObject* out;
10175
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010177 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 if (PyUnicode_READY(self) == -1)
10180 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010183 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010185 if (PyUnicode_IS_ASCII(self))
10186 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010188 PyUnicode_GET_LENGTH(self), maxcount
10189 );
10190 else
10191 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 PyUnicode_GET_LENGTH(self), maxcount
10194 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 case PyUnicode_2BYTE_KIND:
10196 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 PyUnicode_GET_LENGTH(self), maxcount
10199 );
10200 case PyUnicode_4BYTE_KIND:
10201 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 PyUnicode_GET_LENGTH(self), maxcount
10204 );
10205 default:
10206 assert(0);
10207 return NULL;
10208 }
10209
10210 if (PyUnicode_READY(substring) == -1)
10211 return NULL;
10212
10213 kind1 = PyUnicode_KIND(self);
10214 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 len1 = PyUnicode_GET_LENGTH(self);
10216 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010217 if (kind1 < kind2 || len1 < len2) {
10218 out = PyList_New(1);
10219 if (out == NULL)
10220 return NULL;
10221 Py_INCREF(self);
10222 PyList_SET_ITEM(out, 0, self);
10223 return out;
10224 }
10225 buf1 = PyUnicode_DATA(self);
10226 buf2 = PyUnicode_DATA(substring);
10227 if (kind2 != kind1) {
10228 buf2 = _PyUnicode_AsKind(substring, kind1);
10229 if (!buf2)
10230 return NULL;
10231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010233 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10236 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010237 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 else
10239 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010240 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 break;
10242 case PyUnicode_2BYTE_KIND:
10243 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010244 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 break;
10246 case PyUnicode_4BYTE_KIND:
10247 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 break;
10250 default:
10251 out = NULL;
10252 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010253 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 PyMem_Free(buf2);
10255 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010256}
10257
Alexander Belopolsky40018472011-02-26 01:02:56 +000010258static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010259rsplit(PyObject *self,
10260 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010261 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010262{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010263 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 void *buf1, *buf2;
10265 Py_ssize_t len1, len2;
10266 PyObject* out;
10267
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010268 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010269 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 if (PyUnicode_READY(self) == -1)
10272 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010275 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010277 if (PyUnicode_IS_ASCII(self))
10278 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010279 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010280 PyUnicode_GET_LENGTH(self), maxcount
10281 );
10282 else
10283 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010284 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010285 PyUnicode_GET_LENGTH(self), maxcount
10286 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 case PyUnicode_2BYTE_KIND:
10288 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010289 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 PyUnicode_GET_LENGTH(self), maxcount
10291 );
10292 case PyUnicode_4BYTE_KIND:
10293 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010294 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 PyUnicode_GET_LENGTH(self), maxcount
10296 );
10297 default:
10298 assert(0);
10299 return NULL;
10300 }
10301
10302 if (PyUnicode_READY(substring) == -1)
10303 return NULL;
10304
10305 kind1 = PyUnicode_KIND(self);
10306 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 len1 = PyUnicode_GET_LENGTH(self);
10308 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010309 if (kind1 < kind2 || len1 < len2) {
10310 out = PyList_New(1);
10311 if (out == NULL)
10312 return NULL;
10313 Py_INCREF(self);
10314 PyList_SET_ITEM(out, 0, self);
10315 return out;
10316 }
10317 buf1 = PyUnicode_DATA(self);
10318 buf2 = PyUnicode_DATA(substring);
10319 if (kind2 != kind1) {
10320 buf2 = _PyUnicode_AsKind(substring, kind1);
10321 if (!buf2)
10322 return NULL;
10323 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010325 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010327 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10328 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010329 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010330 else
10331 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010332 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 break;
10334 case PyUnicode_2BYTE_KIND:
10335 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010336 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 break;
10338 case PyUnicode_4BYTE_KIND:
10339 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010340 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 break;
10342 default:
10343 out = NULL;
10344 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010345 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 PyMem_Free(buf2);
10347 return out;
10348}
10349
10350static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010351anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10352 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010354 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010355 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010356 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10357 return asciilib_find(buf1, len1, buf2, len2, offset);
10358 else
10359 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 case PyUnicode_2BYTE_KIND:
10361 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10362 case PyUnicode_4BYTE_KIND:
10363 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10364 }
10365 assert(0);
10366 return -1;
10367}
10368
10369static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010370anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10371 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010373 switch (kind) {
10374 case PyUnicode_1BYTE_KIND:
10375 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10376 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10377 else
10378 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10379 case PyUnicode_2BYTE_KIND:
10380 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10381 case PyUnicode_4BYTE_KIND:
10382 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10383 }
10384 assert(0);
10385 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010386}
10387
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010388static void
10389replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10390 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10391{
10392 int kind = PyUnicode_KIND(u);
10393 void *data = PyUnicode_DATA(u);
10394 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10395 if (kind == PyUnicode_1BYTE_KIND) {
10396 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10397 (Py_UCS1 *)data + len,
10398 u1, u2, maxcount);
10399 }
10400 else if (kind == PyUnicode_2BYTE_KIND) {
10401 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10402 (Py_UCS2 *)data + len,
10403 u1, u2, maxcount);
10404 }
10405 else {
10406 assert(kind == PyUnicode_4BYTE_KIND);
10407 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10408 (Py_UCS4 *)data + len,
10409 u1, u2, maxcount);
10410 }
10411}
10412
Alexander Belopolsky40018472011-02-26 01:02:56 +000010413static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414replace(PyObject *self, PyObject *str1,
10415 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010416{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 PyObject *u;
10418 char *sbuf = PyUnicode_DATA(self);
10419 char *buf1 = PyUnicode_DATA(str1);
10420 char *buf2 = PyUnicode_DATA(str2);
10421 int srelease = 0, release1 = 0, release2 = 0;
10422 int skind = PyUnicode_KIND(self);
10423 int kind1 = PyUnicode_KIND(str1);
10424 int kind2 = PyUnicode_KIND(str2);
10425 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10426 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10427 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010428 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010429 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430
10431 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010432 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010434 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435
Victor Stinner59de0ee2011-10-07 10:01:28 +020010436 if (str1 == str2)
10437 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438
Victor Stinner49a0a212011-10-12 23:46:10 +020010439 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010440 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10441 if (maxchar < maxchar_str1)
10442 /* substring too wide to be present */
10443 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010444 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10445 /* Replacing str1 with str2 may cause a maxchar reduction in the
10446 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010447 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010448 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010449
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010451 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010453 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010455 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010456 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010457 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010458
Victor Stinner69ed0f42013-04-09 21:48:24 +020010459 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010460 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010461 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010462 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010463 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010465 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010467
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010468 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10469 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010470 }
10471 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 int rkind = skind;
10473 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010474 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 if (kind1 < rkind) {
10477 /* widen substring */
10478 buf1 = _PyUnicode_AsKind(str1, rkind);
10479 if (!buf1) goto error;
10480 release1 = 1;
10481 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010482 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010483 if (i < 0)
10484 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 if (rkind > kind2) {
10486 /* widen replacement */
10487 buf2 = _PyUnicode_AsKind(str2, rkind);
10488 if (!buf2) goto error;
10489 release2 = 1;
10490 }
10491 else if (rkind < kind2) {
10492 /* widen self and buf1 */
10493 rkind = kind2;
10494 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010495 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 sbuf = _PyUnicode_AsKind(self, rkind);
10497 if (!sbuf) goto error;
10498 srelease = 1;
10499 buf1 = _PyUnicode_AsKind(str1, rkind);
10500 if (!buf1) goto error;
10501 release1 = 1;
10502 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010503 u = PyUnicode_New(slen, maxchar);
10504 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010506 assert(PyUnicode_KIND(u) == rkind);
10507 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010508
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010509 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010510 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010511 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010513 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010514 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010515
10516 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010517 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010518 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010519 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010520 if (i == -1)
10521 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010522 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010524 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010526 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010527 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010528 }
10529 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010531 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 int rkind = skind;
10533 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010536 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 buf1 = _PyUnicode_AsKind(str1, rkind);
10538 if (!buf1) goto error;
10539 release1 = 1;
10540 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010541 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010542 if (n == 0)
10543 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010545 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 buf2 = _PyUnicode_AsKind(str2, rkind);
10547 if (!buf2) goto error;
10548 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010551 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 rkind = kind2;
10553 sbuf = _PyUnicode_AsKind(self, rkind);
10554 if (!sbuf) goto error;
10555 srelease = 1;
10556 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010557 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 buf1 = _PyUnicode_AsKind(str1, rkind);
10559 if (!buf1) goto error;
10560 release1 = 1;
10561 }
10562 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10563 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010564 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 PyErr_SetString(PyExc_OverflowError,
10566 "replace string is too long");
10567 goto error;
10568 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010569 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010571 _Py_INCREF_UNICODE_EMPTY();
10572 if (!unicode_empty)
10573 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010574 u = unicode_empty;
10575 goto done;
10576 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010577 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 PyErr_SetString(PyExc_OverflowError,
10579 "replace string is too long");
10580 goto error;
10581 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010582 u = PyUnicode_New(new_size, maxchar);
10583 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010585 assert(PyUnicode_KIND(u) == rkind);
10586 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 ires = i = 0;
10588 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 while (n-- > 0) {
10590 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010591 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010593 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010594 if (j == -1)
10595 break;
10596 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010598 memcpy(res + rkind * ires,
10599 sbuf + rkind * i,
10600 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010602 }
10603 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010605 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010607 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010609 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010614 memcpy(res + rkind * ires,
10615 sbuf + rkind * i,
10616 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010617 }
10618 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619 /* interleave */
10620 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010621 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010623 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625 if (--n <= 0)
10626 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010627 memcpy(res + rkind * ires,
10628 sbuf + rkind * i,
10629 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 ires++;
10631 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010632 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010633 memcpy(res + rkind * ires,
10634 sbuf + rkind * i,
10635 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010636 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010637 }
10638
10639 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010640 unicode_adjust_maxchar(&u);
10641 if (u == NULL)
10642 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010644
10645 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 if (srelease)
10647 PyMem_FREE(sbuf);
10648 if (release1)
10649 PyMem_FREE(buf1);
10650 if (release2)
10651 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010652 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010654
Benjamin Peterson29060642009-01-31 22:14:21 +000010655 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010656 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 if (srelease)
10658 PyMem_FREE(sbuf);
10659 if (release1)
10660 PyMem_FREE(buf1);
10661 if (release2)
10662 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010663 return unicode_result_unchanged(self);
10664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 error:
10666 if (srelease && sbuf)
10667 PyMem_FREE(sbuf);
10668 if (release1 && buf1)
10669 PyMem_FREE(buf1);
10670 if (release2 && buf2)
10671 PyMem_FREE(buf2);
10672 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673}
10674
10675/* --- Unicode Object Methods --------------------------------------------- */
10676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010677PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010678 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679\n\
10680Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010681characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010682
10683static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010684unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010686 if (PyUnicode_READY(self) == -1)
10687 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010688 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689}
10690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010691PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010692 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693\n\
10694Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010695have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010696
10697static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010698unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010699{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010700 if (PyUnicode_READY(self) == -1)
10701 return NULL;
10702 if (PyUnicode_GET_LENGTH(self) == 0)
10703 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010704 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010705}
10706
Benjamin Petersond5890c82012-01-14 13:23:30 -050010707PyDoc_STRVAR(casefold__doc__,
10708 "S.casefold() -> str\n\
10709\n\
10710Return a version of S suitable for caseless comparisons.");
10711
10712static PyObject *
10713unicode_casefold(PyObject *self)
10714{
10715 if (PyUnicode_READY(self) == -1)
10716 return NULL;
10717 if (PyUnicode_IS_ASCII(self))
10718 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010719 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010720}
10721
10722
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010723/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010724
10725static int
10726convert_uc(PyObject *obj, void *addr)
10727{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010729
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010730 if (!PyUnicode_Check(obj)) {
10731 PyErr_Format(PyExc_TypeError,
10732 "The fill character must be a unicode character, "
10733 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010734 return 0;
10735 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010736 if (PyUnicode_READY(obj) < 0)
10737 return 0;
10738 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010739 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010740 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010741 return 0;
10742 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010743 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010744 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010745}
10746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010747PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010748 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010750Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010751done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752
10753static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010754unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010756 Py_ssize_t marg, left;
10757 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 Py_UCS4 fillchar = ' ';
10759
Victor Stinnere9a29352011-10-01 02:14:59 +020010760 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762
Benjamin Petersonbac79492012-01-14 13:34:47 -050010763 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764 return NULL;
10765
Victor Stinnerc4b49542011-12-11 22:44:26 +010010766 if (PyUnicode_GET_LENGTH(self) >= width)
10767 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
Victor Stinnerc4b49542011-12-11 22:44:26 +010010769 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770 left = marg / 2 + (marg & width & 1);
10771
Victor Stinner9310abb2011-10-05 00:59:23 +020010772 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773}
10774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775/* This function assumes that str1 and str2 are readied by the caller. */
10776
Marc-André Lemburge5034372000-08-08 08:04:29 +000010777static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010778unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010779{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010780#define COMPARE(TYPE1, TYPE2) \
10781 do { \
10782 TYPE1* p1 = (TYPE1 *)data1; \
10783 TYPE2* p2 = (TYPE2 *)data2; \
10784 TYPE1* end = p1 + len; \
10785 Py_UCS4 c1, c2; \
10786 for (; p1 != end; p1++, p2++) { \
10787 c1 = *p1; \
10788 c2 = *p2; \
10789 if (c1 != c2) \
10790 return (c1 < c2) ? -1 : 1; \
10791 } \
10792 } \
10793 while (0)
10794
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 int kind1, kind2;
10796 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010797 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 kind1 = PyUnicode_KIND(str1);
10800 kind2 = PyUnicode_KIND(str2);
10801 data1 = PyUnicode_DATA(str1);
10802 data2 = PyUnicode_DATA(str2);
10803 len1 = PyUnicode_GET_LENGTH(str1);
10804 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010805 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010806
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010807 switch(kind1) {
10808 case PyUnicode_1BYTE_KIND:
10809 {
10810 switch(kind2) {
10811 case PyUnicode_1BYTE_KIND:
10812 {
10813 int cmp = memcmp(data1, data2, len);
10814 /* normalize result of memcmp() into the range [-1; 1] */
10815 if (cmp < 0)
10816 return -1;
10817 if (cmp > 0)
10818 return 1;
10819 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010820 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010821 case PyUnicode_2BYTE_KIND:
10822 COMPARE(Py_UCS1, Py_UCS2);
10823 break;
10824 case PyUnicode_4BYTE_KIND:
10825 COMPARE(Py_UCS1, Py_UCS4);
10826 break;
10827 default:
10828 assert(0);
10829 }
10830 break;
10831 }
10832 case PyUnicode_2BYTE_KIND:
10833 {
10834 switch(kind2) {
10835 case PyUnicode_1BYTE_KIND:
10836 COMPARE(Py_UCS2, Py_UCS1);
10837 break;
10838 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010839 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010840 COMPARE(Py_UCS2, Py_UCS2);
10841 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010842 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 case PyUnicode_4BYTE_KIND:
10844 COMPARE(Py_UCS2, Py_UCS4);
10845 break;
10846 default:
10847 assert(0);
10848 }
10849 break;
10850 }
10851 case PyUnicode_4BYTE_KIND:
10852 {
10853 switch(kind2) {
10854 case PyUnicode_1BYTE_KIND:
10855 COMPARE(Py_UCS4, Py_UCS1);
10856 break;
10857 case PyUnicode_2BYTE_KIND:
10858 COMPARE(Py_UCS4, Py_UCS2);
10859 break;
10860 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010861 {
10862#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10863 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10864 /* normalize result of wmemcmp() into the range [-1; 1] */
10865 if (cmp < 0)
10866 return -1;
10867 if (cmp > 0)
10868 return 1;
10869#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010870 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010871#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010872 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010873 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010874 default:
10875 assert(0);
10876 }
10877 break;
10878 }
10879 default:
10880 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010881 }
10882
Victor Stinner770e19e2012-10-04 22:59:45 +020010883 if (len1 == len2)
10884 return 0;
10885 if (len1 < len2)
10886 return -1;
10887 else
10888 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010889
10890#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010891}
10892
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010893Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010894unicode_compare_eq(PyObject *str1, PyObject *str2)
10895{
10896 int kind;
10897 void *data1, *data2;
10898 Py_ssize_t len;
10899 int cmp;
10900
Victor Stinnere5567ad2012-10-23 02:48:49 +020010901 len = PyUnicode_GET_LENGTH(str1);
10902 if (PyUnicode_GET_LENGTH(str2) != len)
10903 return 0;
10904 kind = PyUnicode_KIND(str1);
10905 if (PyUnicode_KIND(str2) != kind)
10906 return 0;
10907 data1 = PyUnicode_DATA(str1);
10908 data2 = PyUnicode_DATA(str2);
10909
10910 cmp = memcmp(data1, data2, len * kind);
10911 return (cmp == 0);
10912}
10913
10914
Alexander Belopolsky40018472011-02-26 01:02:56 +000010915int
10916PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10919 if (PyUnicode_READY(left) == -1 ||
10920 PyUnicode_READY(right) == -1)
10921 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010922
10923 /* a string is equal to itself */
10924 if (left == right)
10925 return 0;
10926
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010927 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010929 PyErr_Format(PyExc_TypeError,
10930 "Can't compare %.100s and %.100s",
10931 left->ob_type->tp_name,
10932 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933 return -1;
10934}
10935
Martin v. Löwis5b222132007-06-10 09:51:05 +000010936int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010937_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10938{
10939 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10940 if (right_str == NULL)
10941 return -1;
10942 return PyUnicode_Compare(left, right_str);
10943}
10944
10945int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010946PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10947{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 Py_ssize_t i;
10949 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 Py_UCS4 chr;
10951
Victor Stinner910337b2011-10-03 03:20:16 +020010952 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953 if (PyUnicode_READY(uni) == -1)
10954 return -1;
10955 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010956 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010957 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010958 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010959 size_t len, len2 = strlen(str);
10960 int cmp;
10961
10962 len = Py_MIN(len1, len2);
10963 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010964 if (cmp != 0) {
10965 if (cmp < 0)
10966 return -1;
10967 else
10968 return 1;
10969 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010970 if (len1 > len2)
10971 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010972 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010973 return -1; /* str is longer */
10974 return 0;
10975 }
10976 else {
10977 void *data = PyUnicode_DATA(uni);
10978 /* Compare Unicode string and source character set string */
10979 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010980 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010981 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10982 /* This check keeps Python strings that end in '\0' from comparing equal
10983 to C strings identical up to that point. */
10984 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10985 return 1; /* uni is longer */
10986 if (str[i])
10987 return -1; /* str is longer */
10988 return 0;
10989 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010990}
10991
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010992
Benjamin Peterson29060642009-01-31 22:14:21 +000010993#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010994 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010995
Alexander Belopolsky40018472011-02-26 01:02:56 +000010996PyObject *
10997PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010998{
10999 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011000 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011001
Victor Stinnere5567ad2012-10-23 02:48:49 +020011002 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11003 Py_RETURN_NOTIMPLEMENTED;
11004
11005 if (PyUnicode_READY(left) == -1 ||
11006 PyUnicode_READY(right) == -1)
11007 return NULL;
11008
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011009 if (left == right) {
11010 switch (op) {
11011 case Py_EQ:
11012 case Py_LE:
11013 case Py_GE:
11014 /* a string is equal to itself */
11015 v = Py_True;
11016 break;
11017 case Py_NE:
11018 case Py_LT:
11019 case Py_GT:
11020 v = Py_False;
11021 break;
11022 default:
11023 PyErr_BadArgument();
11024 return NULL;
11025 }
11026 }
11027 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011028 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011029 result ^= (op == Py_NE);
11030 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011031 }
11032 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011033 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011034
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011035 /* Convert the return value to a Boolean */
11036 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011037 case Py_LE:
11038 v = TEST_COND(result <= 0);
11039 break;
11040 case Py_GE:
11041 v = TEST_COND(result >= 0);
11042 break;
11043 case Py_LT:
11044 v = TEST_COND(result == -1);
11045 break;
11046 case Py_GT:
11047 v = TEST_COND(result == 1);
11048 break;
11049 default:
11050 PyErr_BadArgument();
11051 return NULL;
11052 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011053 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011054 Py_INCREF(v);
11055 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011056}
11057
Alexander Belopolsky40018472011-02-26 01:02:56 +000011058int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011059_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11060{
11061 return unicode_eq(aa, bb);
11062}
11063
11064int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011065PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011066{
Victor Stinner77282cb2013-04-14 19:22:47 +020011067 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 void *buf1, *buf2;
11069 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011070 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011071
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011072 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011073 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011074 "'in <string>' requires string as left operand, not %.100s",
11075 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011076 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011077 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011078 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011079 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011080 if (ensure_unicode(str) < 0)
11081 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011084 kind2 = PyUnicode_KIND(substr);
11085 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011086 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011087 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011088 len2 = PyUnicode_GET_LENGTH(substr);
11089 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011090 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011091 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011092 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011093 if (len2 == 1) {
11094 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11095 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011096 return result;
11097 }
11098 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011099 buf2 = _PyUnicode_AsKind(substr, kind1);
11100 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011101 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103
Victor Stinner77282cb2013-04-14 19:22:47 +020011104 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 case PyUnicode_1BYTE_KIND:
11106 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11107 break;
11108 case PyUnicode_2BYTE_KIND:
11109 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11110 break;
11111 case PyUnicode_4BYTE_KIND:
11112 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11113 break;
11114 default:
11115 result = -1;
11116 assert(0);
11117 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011118
Victor Stinner77282cb2013-04-14 19:22:47 +020011119 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011120 PyMem_Free(buf2);
11121
Guido van Rossum403d68b2000-03-13 15:55:09 +000011122 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011123}
11124
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125/* Concat to string or Unicode object giving a new Unicode object. */
11126
Alexander Belopolsky40018472011-02-26 01:02:56 +000011127PyObject *
11128PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011130 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011131 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011132 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011134 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136
11137 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011138 if (left == unicode_empty)
11139 return PyUnicode_FromObject(right);
11140 if (right == unicode_empty)
11141 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011143 left_len = PyUnicode_GET_LENGTH(left);
11144 right_len = PyUnicode_GET_LENGTH(right);
11145 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011146 PyErr_SetString(PyExc_OverflowError,
11147 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011148 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011149 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011150 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011151
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011152 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11153 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011154 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011157 result = PyUnicode_New(new_len, maxchar);
11158 if (result == NULL)
11159 return NULL;
11160 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11161 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11162 assert(_PyUnicode_CheckConsistency(result, 1));
11163 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164}
11165
Walter Dörwald1ab83302007-05-18 17:15:44 +000011166void
Victor Stinner23e56682011-10-03 03:54:37 +020011167PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011168{
Victor Stinner23e56682011-10-03 03:54:37 +020011169 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011170 Py_UCS4 maxchar, maxchar2;
11171 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011172
11173 if (p_left == NULL) {
11174 if (!PyErr_Occurred())
11175 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011176 return;
11177 }
Victor Stinner23e56682011-10-03 03:54:37 +020011178 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011179 if (right == NULL || left == NULL
11180 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011181 if (!PyErr_Occurred())
11182 PyErr_BadInternalCall();
11183 goto error;
11184 }
11185
Benjamin Petersonbac79492012-01-14 13:34:47 -050011186 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011187 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011188 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011189 goto error;
11190
Victor Stinner488fa492011-12-12 00:01:39 +010011191 /* Shortcuts */
11192 if (left == unicode_empty) {
11193 Py_DECREF(left);
11194 Py_INCREF(right);
11195 *p_left = right;
11196 return;
11197 }
11198 if (right == unicode_empty)
11199 return;
11200
11201 left_len = PyUnicode_GET_LENGTH(left);
11202 right_len = PyUnicode_GET_LENGTH(right);
11203 if (left_len > PY_SSIZE_T_MAX - right_len) {
11204 PyErr_SetString(PyExc_OverflowError,
11205 "strings are too large to concat");
11206 goto error;
11207 }
11208 new_len = left_len + right_len;
11209
11210 if (unicode_modifiable(left)
11211 && PyUnicode_CheckExact(right)
11212 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011213 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11214 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011215 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011216 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011217 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11218 {
11219 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011220 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011221 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011222
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011223 /* copy 'right' into the newly allocated area of 'left' */
11224 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011225 }
Victor Stinner488fa492011-12-12 00:01:39 +010011226 else {
11227 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11228 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011229 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011230
Victor Stinner488fa492011-12-12 00:01:39 +010011231 /* Concat the two Unicode strings */
11232 res = PyUnicode_New(new_len, maxchar);
11233 if (res == NULL)
11234 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011235 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11236 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011237 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011238 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011239 }
11240 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011241 return;
11242
11243error:
Victor Stinner488fa492011-12-12 00:01:39 +010011244 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011245}
11246
11247void
11248PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11249{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011250 PyUnicode_Append(pleft, right);
11251 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011252}
11253
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011254/*
11255Wraps stringlib_parse_args_finds() and additionally ensures that the
11256first argument is a unicode object.
11257*/
11258
11259Py_LOCAL_INLINE(int)
11260parse_args_finds_unicode(const char * function_name, PyObject *args,
11261 PyObject **substring,
11262 Py_ssize_t *start, Py_ssize_t *end)
11263{
11264 if(stringlib_parse_args_finds(function_name, args, substring,
11265 start, end)) {
11266 if (ensure_unicode(*substring) < 0)
11267 return 0;
11268 return 1;
11269 }
11270 return 0;
11271}
11272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011273PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011274 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011276Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011277string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011278interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
11280static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011281unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011283 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011284 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011285 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011287 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288 void *buf1, *buf2;
11289 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011291 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 kind1 = PyUnicode_KIND(self);
11295 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011296 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011297 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 len1 = PyUnicode_GET_LENGTH(self);
11300 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011302 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011303 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011304
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011305 buf1 = PyUnicode_DATA(self);
11306 buf2 = PyUnicode_DATA(substring);
11307 if (kind2 != kind1) {
11308 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011309 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011310 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011311 }
11312 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 case PyUnicode_1BYTE_KIND:
11314 iresult = ucs1lib_count(
11315 ((Py_UCS1*)buf1) + start, end - start,
11316 buf2, len2, PY_SSIZE_T_MAX
11317 );
11318 break;
11319 case PyUnicode_2BYTE_KIND:
11320 iresult = ucs2lib_count(
11321 ((Py_UCS2*)buf1) + start, end - start,
11322 buf2, len2, PY_SSIZE_T_MAX
11323 );
11324 break;
11325 case PyUnicode_4BYTE_KIND:
11326 iresult = ucs4lib_count(
11327 ((Py_UCS4*)buf1) + start, end - start,
11328 buf2, len2, PY_SSIZE_T_MAX
11329 );
11330 break;
11331 default:
11332 assert(0); iresult = 0;
11333 }
11334
11335 result = PyLong_FromSsize_t(iresult);
11336
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011337 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340 return result;
11341}
11342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011343PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011344 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011346Encode S using the codec registered for encoding. Default encoding\n\
11347is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011348handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011349a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11350'xmlcharrefreplace' as well as any other name registered with\n\
11351codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352
11353static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011354unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011356 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357 char *encoding = NULL;
11358 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011359
Benjamin Peterson308d6372009-09-18 21:42:35 +000011360 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11361 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011363 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011364}
11365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011366PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011367 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368\n\
11369Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011370If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371
11372static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011373unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011375 Py_ssize_t i, j, line_pos, src_len, incr;
11376 Py_UCS4 ch;
11377 PyObject *u;
11378 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011379 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011381 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011382 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383
Ezio Melotti745d54d2013-11-16 19:10:57 +020011384 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11385 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387
Antoine Pitrou22425222011-10-04 19:10:51 +020011388 if (PyUnicode_READY(self) == -1)
11389 return NULL;
11390
Thomas Wouters7e474022000-07-16 12:04:32 +000011391 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011392 src_len = PyUnicode_GET_LENGTH(self);
11393 i = j = line_pos = 0;
11394 kind = PyUnicode_KIND(self);
11395 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011396 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011397 for (; i < src_len; i++) {
11398 ch = PyUnicode_READ(kind, src_data, i);
11399 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011400 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011401 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011402 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011404 goto overflow;
11405 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011407 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011410 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011411 goto overflow;
11412 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011414 if (ch == '\n' || ch == '\r')
11415 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011417 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011418 if (!found)
11419 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011420
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011422 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423 if (!u)
11424 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011425 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
Antoine Pitroue71d5742011-10-04 15:55:09 +020011427 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428
Antoine Pitroue71d5742011-10-04 15:55:09 +020011429 for (; i < src_len; i++) {
11430 ch = PyUnicode_READ(kind, src_data, i);
11431 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011433 incr = tabsize - (line_pos % tabsize);
11434 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011435 FILL(kind, dest_data, ' ', j, incr);
11436 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011438 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011440 line_pos++;
11441 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011442 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011443 if (ch == '\n' || ch == '\r')
11444 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011446 }
11447 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011448 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011449
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011451 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11452 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453}
11454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011455PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457\n\
11458Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011459such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460arguments start and end are interpreted as in slice notation.\n\
11461\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011462Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463
11464static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011467 /* initialize variables to prevent gcc warning */
11468 PyObject *substring = NULL;
11469 Py_ssize_t start = 0;
11470 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011471 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011473 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011476 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011479 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 if (result == -2)
11482 return NULL;
11483
Christian Heimes217cfd12007-12-02 14:31:20 +000011484 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485}
11486
11487static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011488unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011490 void *data;
11491 enum PyUnicode_Kind kind;
11492 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011493
11494 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11495 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011497 }
11498 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11499 PyErr_SetString(PyExc_IndexError, "string index out of range");
11500 return NULL;
11501 }
11502 kind = PyUnicode_KIND(self);
11503 data = PyUnicode_DATA(self);
11504 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011505 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506}
11507
Guido van Rossumc2504932007-09-18 19:42:40 +000011508/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011509 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011510static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011511unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512{
Guido van Rossumc2504932007-09-18 19:42:40 +000011513 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011514 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011515
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011516#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011517 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011518#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 if (_PyUnicode_HASH(self) != -1)
11520 return _PyUnicode_HASH(self);
11521 if (PyUnicode_READY(self) == -1)
11522 return -1;
11523 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011524 /*
11525 We make the hash of the empty string be 0, rather than using
11526 (prefix ^ suffix), since this slightly obfuscates the hash secret
11527 */
11528 if (len == 0) {
11529 _PyUnicode_HASH(self) = 0;
11530 return 0;
11531 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011532 x = _Py_HashBytes(PyUnicode_DATA(self),
11533 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011535 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536}
11537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011538PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011541Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542
11543static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011546 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011547 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011548 PyObject *substring = NULL;
11549 Py_ssize_t start = 0;
11550 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011552 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011555 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011558 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 if (result == -2)
11561 return NULL;
11562
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563 if (result < 0) {
11564 PyErr_SetString(PyExc_ValueError, "substring not found");
11565 return NULL;
11566 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011567
Christian Heimes217cfd12007-12-02 14:31:20 +000011568 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569}
11570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011571PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011572 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011574Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011575at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
11577static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011578unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 Py_ssize_t i, length;
11581 int kind;
11582 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 int cased;
11584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 if (PyUnicode_READY(self) == -1)
11586 return NULL;
11587 length = PyUnicode_GET_LENGTH(self);
11588 kind = PyUnicode_KIND(self);
11589 data = PyUnicode_DATA(self);
11590
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011592 if (length == 1)
11593 return PyBool_FromLong(
11594 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011596 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011598 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011599
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 for (i = 0; i < length; i++) {
11602 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011603
Benjamin Peterson29060642009-01-31 22:14:21 +000011604 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11605 return PyBool_FromLong(0);
11606 else if (!cased && Py_UNICODE_ISLOWER(ch))
11607 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011609 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610}
11611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011612PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011615Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011616at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617
11618static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011619unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 Py_ssize_t i, length;
11622 int kind;
11623 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 int cased;
11625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (PyUnicode_READY(self) == -1)
11627 return NULL;
11628 length = PyUnicode_GET_LENGTH(self);
11629 kind = PyUnicode_KIND(self);
11630 data = PyUnicode_DATA(self);
11631
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (length == 1)
11634 return PyBool_FromLong(
11635 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011637 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011640
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 for (i = 0; i < length; i++) {
11643 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011644
Benjamin Peterson29060642009-01-31 22:14:21 +000011645 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11646 return PyBool_FromLong(0);
11647 else if (!cased && Py_UNICODE_ISUPPER(ch))
11648 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011649 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011650 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651}
11652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011653PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011656Return True if S is a titlecased string and there is at least one\n\
11657character in S, i.e. upper- and titlecase characters may only\n\
11658follow uncased characters and lowercase characters only cased ones.\n\
11659Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660
11661static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011662unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011664 Py_ssize_t i, length;
11665 int kind;
11666 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667 int cased, previous_is_cased;
11668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 if (PyUnicode_READY(self) == -1)
11670 return NULL;
11671 length = PyUnicode_GET_LENGTH(self);
11672 kind = PyUnicode_KIND(self);
11673 data = PyUnicode_DATA(self);
11674
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 if (length == 1) {
11677 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11678 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11679 (Py_UNICODE_ISUPPER(ch) != 0));
11680 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011682 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011684 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011685
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686 cased = 0;
11687 previous_is_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 if (previous_is_cased)
11693 return PyBool_FromLong(0);
11694 previous_is_cased = 1;
11695 cased = 1;
11696 }
11697 else if (Py_UNICODE_ISLOWER(ch)) {
11698 if (!previous_is_cased)
11699 return PyBool_FromLong(0);
11700 previous_is_cased = 1;
11701 cased = 1;
11702 }
11703 else
11704 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011706 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707}
11708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011709PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011710 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011712Return True if all characters in S are whitespace\n\
11713and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714
11715static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011716unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 Py_ssize_t i, length;
11719 int kind;
11720 void *data;
11721
11722 if (PyUnicode_READY(self) == -1)
11723 return NULL;
11724 length = PyUnicode_GET_LENGTH(self);
11725 kind = PyUnicode_KIND(self);
11726 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 if (length == 1)
11730 return PyBool_FromLong(
11731 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011733 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011735 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737 for (i = 0; i < length; i++) {
11738 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011739 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011740 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011742 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743}
11744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011745PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011746 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011747\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011748Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011749and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011750
11751static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011752unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011753{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 Py_ssize_t i, length;
11755 int kind;
11756 void *data;
11757
11758 if (PyUnicode_READY(self) == -1)
11759 return NULL;
11760 length = PyUnicode_GET_LENGTH(self);
11761 kind = PyUnicode_KIND(self);
11762 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011763
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011764 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 1)
11766 return PyBool_FromLong(
11767 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011768
11769 /* 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é Lemburga7acf422000-07-05 09:49:44 +000011772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011773 for (i = 0; i < length; i++) {
11774 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011775 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011776 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011777 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011778}
11779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011780PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011781 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011782\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011783Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011784and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011785
11786static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011787unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011789 int kind;
11790 void *data;
11791 Py_ssize_t len, i;
11792
11793 if (PyUnicode_READY(self) == -1)
11794 return NULL;
11795
11796 kind = PyUnicode_KIND(self);
11797 data = PyUnicode_DATA(self);
11798 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011799
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011800 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 if (len == 1) {
11802 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11803 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11804 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011805
11806 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011808 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 for (i = 0; i < len; i++) {
11811 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011812 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011814 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011815 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011816}
11817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011818PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011821Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011822False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823
11824static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011825unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 Py_ssize_t i, length;
11828 int kind;
11829 void *data;
11830
11831 if (PyUnicode_READY(self) == -1)
11832 return NULL;
11833 length = PyUnicode_GET_LENGTH(self);
11834 kind = PyUnicode_KIND(self);
11835 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011838 if (length == 1)
11839 return PyBool_FromLong(
11840 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011842 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011844 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 for (i = 0; i < length; i++) {
11847 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011850 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851}
11852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011853PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011854 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011856Return True if all characters in S are digits\n\
11857and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858
11859static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011860unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 Py_ssize_t i, length;
11863 int kind;
11864 void *data;
11865
11866 if (PyUnicode_READY(self) == -1)
11867 return NULL;
11868 length = PyUnicode_GET_LENGTH(self);
11869 kind = PyUnicode_KIND(self);
11870 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 if (length == 1) {
11874 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11875 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11876 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011878 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 for (i = 0; i < length; i++) {
11883 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011886 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887}
11888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011889PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011892Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011893False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894
11895static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011896unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011898 Py_ssize_t i, length;
11899 int kind;
11900 void *data;
11901
11902 if (PyUnicode_READY(self) == -1)
11903 return NULL;
11904 length = PyUnicode_GET_LENGTH(self);
11905 kind = PyUnicode_KIND(self);
11906 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 if (length == 1)
11910 return PyBool_FromLong(
11911 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011913 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 for (i = 0; i < length; i++) {
11918 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011919 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011921 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922}
11923
Martin v. Löwis47383402007-08-15 07:32:56 +000011924int
11925PyUnicode_IsIdentifier(PyObject *self)
11926{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 int kind;
11928 void *data;
11929 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011930 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011931
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 if (PyUnicode_READY(self) == -1) {
11933 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011934 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 }
11936
11937 /* Special case for empty strings */
11938 if (PyUnicode_GET_LENGTH(self) == 0)
11939 return 0;
11940 kind = PyUnicode_KIND(self);
11941 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011942
11943 /* PEP 3131 says that the first character must be in
11944 XID_Start and subsequent characters in XID_Continue,
11945 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011946 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011947 letters, digits, underscore). However, given the current
11948 definition of XID_Start and XID_Continue, it is sufficient
11949 to check just for these, except that _ must be allowed
11950 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011952 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011953 return 0;
11954
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011955 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011957 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011958 return 1;
11959}
11960
11961PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011962 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011963\n\
11964Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011965to the language definition.\n\
11966\n\
11967Use keyword.iskeyword() to test for reserved identifiers\n\
11968such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011969
11970static PyObject*
11971unicode_isidentifier(PyObject *self)
11972{
11973 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11974}
11975
Georg Brandl559e5d72008-06-11 18:37:52 +000011976PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011977 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011978\n\
11979Return True if all characters in S are considered\n\
11980printable in repr() or S is empty, False otherwise.");
11981
11982static PyObject*
11983unicode_isprintable(PyObject *self)
11984{
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);
Georg Brandl559e5d72008-06-11 18:37:52 +000011994
11995 /* 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_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 for (i = 0; i < length; i++) {
12001 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012002 Py_RETURN_FALSE;
12003 }
12004 }
12005 Py_RETURN_TRUE;
12006}
12007
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012008PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012009 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012010\n\
12011Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012012iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013
12014static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012015unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012017 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018}
12019
Martin v. Löwis18e16552006-02-15 17:27:45 +000012020static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012021unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 if (PyUnicode_READY(self) == -1)
12024 return -1;
12025 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012026}
12027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012028PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012029 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012031Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012032done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033
12034static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012035unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012036{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012037 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 Py_UCS4 fillchar = ' ';
12039
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012040 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041 return NULL;
12042
Benjamin Petersonbac79492012-01-14 13:34:47 -050012043 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045
Victor Stinnerc4b49542011-12-11 22:44:26 +010012046 if (PyUnicode_GET_LENGTH(self) >= width)
12047 return unicode_result_unchanged(self);
12048
12049 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050}
12051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012052PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012053 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012055Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056
12057static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012058unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012060 if (PyUnicode_READY(self) == -1)
12061 return NULL;
12062 if (PyUnicode_IS_ASCII(self))
12063 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012064 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065}
12066
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012067#define LEFTSTRIP 0
12068#define RIGHTSTRIP 1
12069#define BOTHSTRIP 2
12070
12071/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012072static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012073
12074#define STRIPNAME(i) (stripformat[i]+3)
12075
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012076/* externally visible for str.strip(unicode) */
12077PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012078_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012079{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 void *data;
12081 int kind;
12082 Py_ssize_t i, j, len;
12083 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012084 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12087 return NULL;
12088
12089 kind = PyUnicode_KIND(self);
12090 data = PyUnicode_DATA(self);
12091 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012092 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12094 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012095 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012096
Benjamin Peterson14339b62009-01-31 16:36:08 +000012097 i = 0;
12098 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012099 while (i < len) {
12100 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12101 if (!BLOOM(sepmask, ch))
12102 break;
12103 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12104 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012105 i++;
12106 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012107 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012108
Benjamin Peterson14339b62009-01-31 16:36:08 +000012109 j = len;
12110 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012111 j--;
12112 while (j >= i) {
12113 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12114 if (!BLOOM(sepmask, ch))
12115 break;
12116 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12117 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012118 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012119 }
12120
Benjamin Peterson29060642009-01-31 22:14:21 +000012121 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012122 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012123
Victor Stinner7931d9a2011-11-04 00:22:48 +010012124 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125}
12126
12127PyObject*
12128PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12129{
12130 unsigned char *data;
12131 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012132 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133
Victor Stinnerde636f32011-10-01 03:55:54 +020012134 if (PyUnicode_READY(self) == -1)
12135 return NULL;
12136
Victor Stinner684d5fd2012-05-03 02:32:34 +020012137 length = PyUnicode_GET_LENGTH(self);
12138 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012139
Victor Stinner684d5fd2012-05-03 02:32:34 +020012140 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012141 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142
Victor Stinnerde636f32011-10-01 03:55:54 +020012143 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012144 PyErr_SetString(PyExc_IndexError, "string index out of range");
12145 return NULL;
12146 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012147 if (start >= length || end < start)
12148 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012149
Victor Stinner684d5fd2012-05-03 02:32:34 +020012150 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012151 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012152 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012153 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012154 }
12155 else {
12156 kind = PyUnicode_KIND(self);
12157 data = PyUnicode_1BYTE_DATA(self);
12158 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012159 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012160 length);
12161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163
12164static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012165do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 Py_ssize_t len, i, j;
12168
12169 if (PyUnicode_READY(self) == -1)
12170 return NULL;
12171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012173
Victor Stinnercc7af722013-04-09 22:39:24 +020012174 if (PyUnicode_IS_ASCII(self)) {
12175 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12176
12177 i = 0;
12178 if (striptype != RIGHTSTRIP) {
12179 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012180 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012181 if (!_Py_ascii_whitespace[ch])
12182 break;
12183 i++;
12184 }
12185 }
12186
12187 j = len;
12188 if (striptype != LEFTSTRIP) {
12189 j--;
12190 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012191 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012192 if (!_Py_ascii_whitespace[ch])
12193 break;
12194 j--;
12195 }
12196 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012197 }
12198 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012199 else {
12200 int kind = PyUnicode_KIND(self);
12201 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012202
Victor Stinnercc7af722013-04-09 22:39:24 +020012203 i = 0;
12204 if (striptype != RIGHTSTRIP) {
12205 while (i < len) {
12206 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12207 if (!Py_UNICODE_ISSPACE(ch))
12208 break;
12209 i++;
12210 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012211 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012212
12213 j = len;
12214 if (striptype != LEFTSTRIP) {
12215 j--;
12216 while (j >= i) {
12217 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12218 if (!Py_UNICODE_ISSPACE(ch))
12219 break;
12220 j--;
12221 }
12222 j++;
12223 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012224 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012225
Victor Stinner7931d9a2011-11-04 00:22:48 +010012226 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227}
12228
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012229
12230static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012231do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012232{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012233 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012234
Serhiy Storchakac6792272013-10-19 21:03:34 +030012235 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012236 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012237
Benjamin Peterson14339b62009-01-31 16:36:08 +000012238 if (sep != NULL && sep != Py_None) {
12239 if (PyUnicode_Check(sep))
12240 return _PyUnicode_XStrip(self, striptype, sep);
12241 else {
12242 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012243 "%s arg must be None or str",
12244 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012245 return NULL;
12246 }
12247 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012248
Benjamin Peterson14339b62009-01-31 16:36:08 +000012249 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012250}
12251
12252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012253PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012255\n\
12256Return a copy of the string S with leading and trailing\n\
12257whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012258If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012259
12260static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012261unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012262{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012263 if (PyTuple_GET_SIZE(args) == 0)
12264 return do_strip(self, BOTHSTRIP); /* Common case */
12265 else
12266 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012267}
12268
12269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012270PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012271 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012272\n\
12273Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012274If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012275
12276static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012277unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012278{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012279 if (PyTuple_GET_SIZE(args) == 0)
12280 return do_strip(self, LEFTSTRIP); /* Common case */
12281 else
12282 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012283}
12284
12285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012286PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012287 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012288\n\
12289Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012290If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012291
12292static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012293unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012294{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012295 if (PyTuple_GET_SIZE(args) == 0)
12296 return do_strip(self, RIGHTSTRIP); /* Common case */
12297 else
12298 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012299}
12300
12301
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012303unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012304{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012305 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012307
Serhiy Storchaka05997252013-01-26 12:14:02 +020012308 if (len < 1)
12309 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012310
Victor Stinnerc4b49542011-12-11 22:44:26 +010012311 /* no repeat, return original string */
12312 if (len == 1)
12313 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012314
Benjamin Petersonbac79492012-01-14 13:34:47 -050012315 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 return NULL;
12317
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012318 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012319 PyErr_SetString(PyExc_OverflowError,
12320 "repeated string is too long");
12321 return NULL;
12322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012324
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012325 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012326 if (!u)
12327 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012328 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 if (PyUnicode_GET_LENGTH(str) == 1) {
12331 const int kind = PyUnicode_KIND(str);
12332 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012333 if (kind == PyUnicode_1BYTE_KIND) {
12334 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012335 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012336 }
12337 else if (kind == PyUnicode_2BYTE_KIND) {
12338 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012339 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012340 ucs2[n] = fill_char;
12341 } else {
12342 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12343 assert(kind == PyUnicode_4BYTE_KIND);
12344 for (n = 0; n < len; ++n)
12345 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012346 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 }
12348 else {
12349 /* number of characters copied this far */
12350 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012351 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 char *to = (char *) PyUnicode_DATA(u);
12353 Py_MEMCPY(to, PyUnicode_DATA(str),
12354 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 n = (done <= nchars-done) ? done : nchars-done;
12357 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360 }
12361
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012362 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012363 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012364}
12365
Alexander Belopolsky40018472011-02-26 01:02:56 +000012366PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012367PyUnicode_Replace(PyObject *str,
12368 PyObject *substr,
12369 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012370 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012372 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12373 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012374 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012375 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012376}
12377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012378PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012379 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380\n\
12381Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012382old replaced by new. If the optional argument count is\n\
12383given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012384
12385static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 PyObject *str1;
12389 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012390 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012392 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012394 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012395 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012396 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397}
12398
Alexander Belopolsky40018472011-02-26 01:02:56 +000012399static PyObject *
12400unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012401{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012402 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 Py_ssize_t isize;
12404 Py_ssize_t osize, squote, dquote, i, o;
12405 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012406 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012407 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012410 return NULL;
12411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412 isize = PyUnicode_GET_LENGTH(unicode);
12413 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 /* Compute length of output, quote characters, and
12416 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012417 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 max = 127;
12419 squote = dquote = 0;
12420 ikind = PyUnicode_KIND(unicode);
12421 for (i = 0; i < isize; i++) {
12422 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012423 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012425 case '\'': squote++; break;
12426 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012428 incr = 2;
12429 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012430 default:
12431 /* Fast-path ASCII */
12432 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012433 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012435 ;
12436 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012438 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012439 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012441 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012443 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012444 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012445 if (osize > PY_SSIZE_T_MAX - incr) {
12446 PyErr_SetString(PyExc_OverflowError,
12447 "string is too long to generate repr");
12448 return NULL;
12449 }
12450 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 }
12452
12453 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012454 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012456 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 if (dquote)
12458 /* Both squote and dquote present. Use squote,
12459 and escape them */
12460 osize += squote;
12461 else
12462 quote = '"';
12463 }
Victor Stinner55c08782013-04-14 18:45:39 +020012464 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012465
12466 repr = PyUnicode_New(osize, max);
12467 if (repr == NULL)
12468 return NULL;
12469 okind = PyUnicode_KIND(repr);
12470 odata = PyUnicode_DATA(repr);
12471
12472 PyUnicode_WRITE(okind, odata, 0, quote);
12473 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012474 if (unchanged) {
12475 _PyUnicode_FastCopyCharacters(repr, 1,
12476 unicode, 0,
12477 isize);
12478 }
12479 else {
12480 for (i = 0, o = 1; i < isize; i++) {
12481 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482
Victor Stinner55c08782013-04-14 18:45:39 +020012483 /* Escape quotes and backslashes */
12484 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012485 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012487 continue;
12488 }
12489
12490 /* Map special whitespace to '\t', \n', '\r' */
12491 if (ch == '\t') {
12492 PyUnicode_WRITE(okind, odata, o++, '\\');
12493 PyUnicode_WRITE(okind, odata, o++, 't');
12494 }
12495 else if (ch == '\n') {
12496 PyUnicode_WRITE(okind, odata, o++, '\\');
12497 PyUnicode_WRITE(okind, odata, o++, 'n');
12498 }
12499 else if (ch == '\r') {
12500 PyUnicode_WRITE(okind, odata, o++, '\\');
12501 PyUnicode_WRITE(okind, odata, o++, 'r');
12502 }
12503
12504 /* Map non-printable US ASCII to '\xhh' */
12505 else if (ch < ' ' || ch == 0x7F) {
12506 PyUnicode_WRITE(okind, odata, o++, '\\');
12507 PyUnicode_WRITE(okind, odata, o++, 'x');
12508 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12509 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12510 }
12511
12512 /* Copy ASCII characters as-is */
12513 else if (ch < 0x7F) {
12514 PyUnicode_WRITE(okind, odata, o++, ch);
12515 }
12516
12517 /* Non-ASCII characters */
12518 else {
12519 /* Map Unicode whitespace and control characters
12520 (categories Z* and C* except ASCII space)
12521 */
12522 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12523 PyUnicode_WRITE(okind, odata, o++, '\\');
12524 /* Map 8-bit characters to '\xhh' */
12525 if (ch <= 0xff) {
12526 PyUnicode_WRITE(okind, odata, o++, 'x');
12527 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12528 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12529 }
12530 /* Map 16-bit characters to '\uxxxx' */
12531 else if (ch <= 0xffff) {
12532 PyUnicode_WRITE(okind, odata, o++, 'u');
12533 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12534 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12535 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12536 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12537 }
12538 /* Map 21-bit characters to '\U00xxxxxx' */
12539 else {
12540 PyUnicode_WRITE(okind, odata, o++, 'U');
12541 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12542 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12543 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12544 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12545 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12546 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12547 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12548 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12549 }
12550 }
12551 /* Copy characters as-is */
12552 else {
12553 PyUnicode_WRITE(okind, odata, o++, ch);
12554 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012555 }
12556 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012559 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012560 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561}
12562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012563PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012564 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565\n\
12566Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012567such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568arguments start and end are interpreted as in slice notation.\n\
12569\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012570Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012571
12572static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012575 /* initialize variables to prevent gcc warning */
12576 PyObject *substring = NULL;
12577 Py_ssize_t start = 0;
12578 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012579 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012581 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012582 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012584 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012587 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 if (result == -2)
12590 return NULL;
12591
Christian Heimes217cfd12007-12-02 14:31:20 +000012592 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593}
12594
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012595PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012596 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012598Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599
12600static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012603 /* initialize variables to prevent gcc warning */
12604 PyObject *substring = NULL;
12605 Py_ssize_t start = 0;
12606 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012607 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012609 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012610 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012612 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012614
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012615 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617 if (result == -2)
12618 return NULL;
12619
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620 if (result < 0) {
12621 PyErr_SetString(PyExc_ValueError, "substring not found");
12622 return NULL;
12623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624
Christian Heimes217cfd12007-12-02 14:31:20 +000012625 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626}
12627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012628PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012629 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012631Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012632done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633
12634static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012635unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012637 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012638 Py_UCS4 fillchar = ' ';
12639
Victor Stinnere9a29352011-10-01 02:14:59 +020012640 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012641 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012642
Benjamin Petersonbac79492012-01-14 13:34:47 -050012643 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644 return NULL;
12645
Victor Stinnerc4b49542011-12-11 22:44:26 +010012646 if (PyUnicode_GET_LENGTH(self) >= width)
12647 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648
Victor Stinnerc4b49542011-12-11 22:44:26 +010012649 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650}
12651
Alexander Belopolsky40018472011-02-26 01:02:56 +000012652PyObject *
12653PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012655 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012656 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012658 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659}
12660
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012661PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012662 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663\n\
12664Return a list of the words in S, using sep as the\n\
12665delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012666splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012667whitespace string is a separator and empty strings are\n\
12668removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669
12670static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012671unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012672{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012673 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012675 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012677 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12678 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679 return NULL;
12680
12681 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012682 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012683
12684 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012685 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012686
12687 PyErr_Format(PyExc_TypeError,
12688 "must be str or None, not %.100s",
12689 Py_TYPE(substring)->tp_name);
12690 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691}
12692
Thomas Wouters477c8d52006-05-27 19:21:47 +000012693PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012694PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012695{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012696 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012697 int kind1, kind2;
12698 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012699 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012701 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012702 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012703
Victor Stinner14f8f022011-10-05 20:58:25 +020012704 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 len1 = PyUnicode_GET_LENGTH(str_obj);
12707 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012708 if (kind1 < kind2 || len1 < len2) {
12709 _Py_INCREF_UNICODE_EMPTY();
12710 if (!unicode_empty)
12711 out = NULL;
12712 else {
12713 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12714 Py_DECREF(unicode_empty);
12715 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012716 return out;
12717 }
12718 buf1 = PyUnicode_DATA(str_obj);
12719 buf2 = PyUnicode_DATA(sep_obj);
12720 if (kind2 != kind1) {
12721 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12722 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012723 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012724 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012726 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012728 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12729 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12730 else
12731 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012732 break;
12733 case PyUnicode_2BYTE_KIND:
12734 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12735 break;
12736 case PyUnicode_4BYTE_KIND:
12737 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12738 break;
12739 default:
12740 assert(0);
12741 out = 0;
12742 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012743
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012744 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746
12747 return out;
12748}
12749
12750
12751PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012752PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012753{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012754 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012755 int kind1, kind2;
12756 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012757 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012758
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012759 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012760 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012761
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012762 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 len1 = PyUnicode_GET_LENGTH(str_obj);
12765 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012766 if (kind1 < kind2 || len1 < len2) {
12767 _Py_INCREF_UNICODE_EMPTY();
12768 if (!unicode_empty)
12769 out = NULL;
12770 else {
12771 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12772 Py_DECREF(unicode_empty);
12773 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012774 return out;
12775 }
12776 buf1 = PyUnicode_DATA(str_obj);
12777 buf2 = PyUnicode_DATA(sep_obj);
12778 if (kind2 != kind1) {
12779 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12780 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012781 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012784 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012785 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012786 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12787 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12788 else
12789 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012790 break;
12791 case PyUnicode_2BYTE_KIND:
12792 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12793 break;
12794 case PyUnicode_4BYTE_KIND:
12795 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12796 break;
12797 default:
12798 assert(0);
12799 out = 0;
12800 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012801
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012802 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012804
12805 return out;
12806}
12807
12808PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012810\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012811Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012812the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012813found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012814
12815static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012816unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012817{
Victor Stinner9310abb2011-10-05 00:59:23 +020012818 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012819}
12820
12821PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012822 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012823\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012824Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012825the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012826separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012827
12828static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012829unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012830{
Victor Stinner9310abb2011-10-05 00:59:23 +020012831 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832}
12833
Alexander Belopolsky40018472011-02-26 01:02:56 +000012834PyObject *
12835PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012836{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012837 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012838 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012839
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012840 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012841}
12842
12843PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012844 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012845\n\
12846Return a list of the words in S, using sep as the\n\
12847delimiter string, starting at the end of the string and\n\
12848working to the front. If maxsplit is given, at most maxsplit\n\
12849splits are done. If sep is not specified, any whitespace string\n\
12850is a separator.");
12851
12852static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012853unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012854{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012855 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012856 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012857 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012858
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012859 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12860 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012861 return NULL;
12862
12863 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012864 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012865
12866 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012867 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012868
12869 PyErr_Format(PyExc_TypeError,
12870 "must be str or None, not %.100s",
12871 Py_TYPE(substring)->tp_name);
12872 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012873}
12874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012875PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012876 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877\n\
12878Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012879Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012880is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881
12882static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012883unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012885 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012886 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012888 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12889 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890 return NULL;
12891
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012892 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893}
12894
12895static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012896PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012898 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899}
12900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012901PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012902 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903\n\
12904Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012905and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906
12907static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012908unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012909{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012910 if (PyUnicode_READY(self) == -1)
12911 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012912 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913}
12914
Larry Hastings61272b72014-01-07 12:41:53 -080012915/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012916
Larry Hastings31826802013-10-19 00:09:25 -070012917@staticmethod
12918str.maketrans as unicode_maketrans
12919
12920 x: object
12921
12922 y: unicode=NULL
12923
12924 z: unicode=NULL
12925
12926 /
12927
12928Return a translation table usable for str.translate().
12929
12930If there is only one argument, it must be a dictionary mapping Unicode
12931ordinals (integers) or characters to Unicode ordinals, strings or None.
12932Character keys will be then converted to ordinals.
12933If there are two arguments, they must be strings of equal length, and
12934in the resulting dictionary, each character in x will be mapped to the
12935character at the same position in y. If there is a third argument, it
12936must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012937[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012938
Larry Hastings31826802013-10-19 00:09:25 -070012939static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012940unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012941/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012942{
Georg Brandlceee0772007-11-27 23:48:05 +000012943 PyObject *new = NULL, *key, *value;
12944 Py_ssize_t i = 0;
12945 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012946
Georg Brandlceee0772007-11-27 23:48:05 +000012947 new = PyDict_New();
12948 if (!new)
12949 return NULL;
12950 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 int x_kind, y_kind, z_kind;
12952 void *x_data, *y_data, *z_data;
12953
Georg Brandlceee0772007-11-27 23:48:05 +000012954 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012955 if (!PyUnicode_Check(x)) {
12956 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12957 "be a string if there is a second argument");
12958 goto err;
12959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012961 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12962 "arguments must have equal length");
12963 goto err;
12964 }
12965 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 x_kind = PyUnicode_KIND(x);
12967 y_kind = PyUnicode_KIND(y);
12968 x_data = PyUnicode_DATA(x);
12969 y_data = PyUnicode_DATA(y);
12970 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12971 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012972 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012973 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012974 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012975 if (!value) {
12976 Py_DECREF(key);
12977 goto err;
12978 }
Georg Brandlceee0772007-11-27 23:48:05 +000012979 res = PyDict_SetItem(new, key, value);
12980 Py_DECREF(key);
12981 Py_DECREF(value);
12982 if (res < 0)
12983 goto err;
12984 }
12985 /* create entries for deleting chars in z */
12986 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 z_kind = PyUnicode_KIND(z);
12988 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012989 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012991 if (!key)
12992 goto err;
12993 res = PyDict_SetItem(new, key, Py_None);
12994 Py_DECREF(key);
12995 if (res < 0)
12996 goto err;
12997 }
12998 }
12999 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 int kind;
13001 void *data;
13002
Georg Brandlceee0772007-11-27 23:48:05 +000013003 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013004 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013005 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13006 "to maketrans it must be a dict");
13007 goto err;
13008 }
13009 /* copy entries into the new dict, converting string keys to int keys */
13010 while (PyDict_Next(x, &i, &key, &value)) {
13011 if (PyUnicode_Check(key)) {
13012 /* convert string keys to integer keys */
13013 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013014 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013015 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13016 "table must be of length 1");
13017 goto err;
13018 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 kind = PyUnicode_KIND(key);
13020 data = PyUnicode_DATA(key);
13021 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013022 if (!newkey)
13023 goto err;
13024 res = PyDict_SetItem(new, newkey, value);
13025 Py_DECREF(newkey);
13026 if (res < 0)
13027 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013028 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013029 /* just keep integer keys */
13030 if (PyDict_SetItem(new, key, value) < 0)
13031 goto err;
13032 } else {
13033 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13034 "be strings or integers");
13035 goto err;
13036 }
13037 }
13038 }
13039 return new;
13040 err:
13041 Py_DECREF(new);
13042 return NULL;
13043}
13044
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013045PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013046 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013048Return a copy of the string S in which each character has been mapped\n\
13049through the given translation table. The table must implement\n\
13050lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13051mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13052this operation raises LookupError, the character is left untouched.\n\
13053Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054
13055static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013056unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013058 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059}
13060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013061PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013062 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013063\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013064Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065
13066static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013067unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013069 if (PyUnicode_READY(self) == -1)
13070 return NULL;
13071 if (PyUnicode_IS_ASCII(self))
13072 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013073 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074}
13075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013076PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013077 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013079Pad a numeric string S with zeros on the left, to fill a field\n\
13080of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013081
13082static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013083unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013085 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013086 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013087 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013088 int kind;
13089 void *data;
13090 Py_UCS4 chr;
13091
Martin v. Löwis18e16552006-02-15 17:27:45 +000013092 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093 return NULL;
13094
Benjamin Petersonbac79492012-01-14 13:34:47 -050013095 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013096 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097
Victor Stinnerc4b49542011-12-11 22:44:26 +010013098 if (PyUnicode_GET_LENGTH(self) >= width)
13099 return unicode_result_unchanged(self);
13100
13101 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102
13103 u = pad(self, fill, 0, '0');
13104
Walter Dörwald068325e2002-04-15 13:36:47 +000013105 if (u == NULL)
13106 return NULL;
13107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013108 kind = PyUnicode_KIND(u);
13109 data = PyUnicode_DATA(u);
13110 chr = PyUnicode_READ(kind, data, fill);
13111
13112 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013114 PyUnicode_WRITE(kind, data, 0, chr);
13115 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116 }
13117
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013118 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013119 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121
13122#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013123static PyObject *
13124unicode__decimal2ascii(PyObject *self)
13125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013126 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013127}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128#endif
13129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013130PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013131 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013133Return True if S starts with the specified prefix, False otherwise.\n\
13134With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013135With optional end, stop comparing S at that position.\n\
13136prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013137
13138static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013139unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013142 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013143 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013144 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013145 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013146 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147
Jesus Ceaac451502011-04-20 17:09:23 +020013148 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013149 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013150 if (PyTuple_Check(subobj)) {
13151 Py_ssize_t i;
13152 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013153 substring = PyTuple_GET_ITEM(subobj, i);
13154 if (!PyUnicode_Check(substring)) {
13155 PyErr_Format(PyExc_TypeError,
13156 "tuple for startswith must only contain str, "
13157 "not %.100s",
13158 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013159 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013160 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013161 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013162 if (result == -1)
13163 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013164 if (result) {
13165 Py_RETURN_TRUE;
13166 }
13167 }
13168 /* nothing matched */
13169 Py_RETURN_FALSE;
13170 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013171 if (!PyUnicode_Check(subobj)) {
13172 PyErr_Format(PyExc_TypeError,
13173 "startswith first arg must be str or "
13174 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013176 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013177 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013178 if (result == -1)
13179 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181}
13182
13183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013184PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013187Return True if S ends with the specified suffix, False otherwise.\n\
13188With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013189With optional end, stop comparing S at that position.\n\
13190suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191
13192static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013193unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013194 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013196 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013197 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013198 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013199 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013200 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201
Jesus Ceaac451502011-04-20 17:09:23 +020013202 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013203 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013204 if (PyTuple_Check(subobj)) {
13205 Py_ssize_t i;
13206 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013207 substring = PyTuple_GET_ITEM(subobj, i);
13208 if (!PyUnicode_Check(substring)) {
13209 PyErr_Format(PyExc_TypeError,
13210 "tuple for endswith must only contain str, "
13211 "not %.100s",
13212 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013214 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013215 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013216 if (result == -1)
13217 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013218 if (result) {
13219 Py_RETURN_TRUE;
13220 }
13221 }
13222 Py_RETURN_FALSE;
13223 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013224 if (!PyUnicode_Check(subobj)) {
13225 PyErr_Format(PyExc_TypeError,
13226 "endswith first arg must be str or "
13227 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013229 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013230 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013231 if (result == -1)
13232 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013233 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234}
13235
Victor Stinner202fdca2012-05-07 12:47:02 +020013236Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013237_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013238{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013239 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13240 writer->data = PyUnicode_DATA(writer->buffer);
13241
13242 if (!writer->readonly) {
13243 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013244 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013245 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013246 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013247 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13248 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13249 writer->kind = PyUnicode_WCHAR_KIND;
13250 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13251
Victor Stinner8f674cc2013-04-17 23:02:17 +020013252 /* Copy-on-write mode: set buffer size to 0 so
13253 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13254 * next write. */
13255 writer->size = 0;
13256 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013257}
13258
Victor Stinnerd3f08822012-05-29 12:57:52 +020013259void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013260_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013261{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013262 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013263
13264 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013265 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013266
13267 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13268 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13269 writer->kind = PyUnicode_WCHAR_KIND;
13270 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013271}
13272
Victor Stinnerd3f08822012-05-29 12:57:52 +020013273int
13274_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13275 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013276{
13277 Py_ssize_t newlen;
13278 PyObject *newbuffer;
13279
Victor Stinnerca9381e2015-09-22 00:58:32 +020013280 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013281 assert((maxchar > writer->maxchar && length >= 0)
13282 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013283
Victor Stinner202fdca2012-05-07 12:47:02 +020013284 if (length > PY_SSIZE_T_MAX - writer->pos) {
13285 PyErr_NoMemory();
13286 return -1;
13287 }
13288 newlen = writer->pos + length;
13289
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013290 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013291
Victor Stinnerd3f08822012-05-29 12:57:52 +020013292 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013293 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013294 if (writer->overallocate
13295 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13296 /* overallocate to limit the number of realloc() */
13297 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013298 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013299 if (newlen < writer->min_length)
13300 newlen = writer->min_length;
13301
Victor Stinnerd3f08822012-05-29 12:57:52 +020013302 writer->buffer = PyUnicode_New(newlen, maxchar);
13303 if (writer->buffer == NULL)
13304 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013305 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013306 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013307 if (writer->overallocate
13308 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13309 /* overallocate to limit the number of realloc() */
13310 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013311 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013312 if (newlen < writer->min_length)
13313 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013314
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013315 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013316 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013317 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013318 newbuffer = PyUnicode_New(newlen, maxchar);
13319 if (newbuffer == NULL)
13320 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13322 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013323 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013324 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013325 }
13326 else {
13327 newbuffer = resize_compact(writer->buffer, newlen);
13328 if (newbuffer == NULL)
13329 return -1;
13330 }
13331 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013332 }
13333 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013334 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013335 newbuffer = PyUnicode_New(writer->size, maxchar);
13336 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013337 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013338 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13339 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013340 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013341 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013342 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013343 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013344
13345#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013346}
13347
Victor Stinnerca9381e2015-09-22 00:58:32 +020013348int
13349_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13350 enum PyUnicode_Kind kind)
13351{
13352 Py_UCS4 maxchar;
13353
13354 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13355 assert(writer->kind < kind);
13356
13357 switch (kind)
13358 {
13359 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13360 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13361 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13362 default:
13363 assert(0 && "invalid kind");
13364 return -1;
13365 }
13366
13367 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13368}
13369
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013370Py_LOCAL_INLINE(int)
13371_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013372{
13373 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13374 return -1;
13375 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13376 writer->pos++;
13377 return 0;
13378}
13379
13380int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013381_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13382{
13383 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13384}
13385
13386int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013387_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13388{
13389 Py_UCS4 maxchar;
13390 Py_ssize_t len;
13391
13392 if (PyUnicode_READY(str) == -1)
13393 return -1;
13394 len = PyUnicode_GET_LENGTH(str);
13395 if (len == 0)
13396 return 0;
13397 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13398 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013399 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013400 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013401 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013402 Py_INCREF(str);
13403 writer->buffer = str;
13404 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013405 writer->pos += len;
13406 return 0;
13407 }
13408 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13409 return -1;
13410 }
13411 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13412 str, 0, len);
13413 writer->pos += len;
13414 return 0;
13415}
13416
Victor Stinnere215d962012-10-06 23:03:36 +020013417int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013418_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13419 Py_ssize_t start, Py_ssize_t end)
13420{
13421 Py_UCS4 maxchar;
13422 Py_ssize_t len;
13423
13424 if (PyUnicode_READY(str) == -1)
13425 return -1;
13426
13427 assert(0 <= start);
13428 assert(end <= PyUnicode_GET_LENGTH(str));
13429 assert(start <= end);
13430
13431 if (end == 0)
13432 return 0;
13433
13434 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13435 return _PyUnicodeWriter_WriteStr(writer, str);
13436
13437 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13438 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13439 else
13440 maxchar = writer->maxchar;
13441 len = end - start;
13442
13443 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13444 return -1;
13445
13446 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13447 str, start, len);
13448 writer->pos += len;
13449 return 0;
13450}
13451
13452int
Victor Stinner4a587072013-11-19 12:54:53 +010013453_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13454 const char *ascii, Py_ssize_t len)
13455{
13456 if (len == -1)
13457 len = strlen(ascii);
13458
13459 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13460
13461 if (writer->buffer == NULL && !writer->overallocate) {
13462 PyObject *str;
13463
13464 str = _PyUnicode_FromASCII(ascii, len);
13465 if (str == NULL)
13466 return -1;
13467
13468 writer->readonly = 1;
13469 writer->buffer = str;
13470 _PyUnicodeWriter_Update(writer);
13471 writer->pos += len;
13472 return 0;
13473 }
13474
13475 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13476 return -1;
13477
13478 switch (writer->kind)
13479 {
13480 case PyUnicode_1BYTE_KIND:
13481 {
13482 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13483 Py_UCS1 *data = writer->data;
13484
13485 Py_MEMCPY(data + writer->pos, str, len);
13486 break;
13487 }
13488 case PyUnicode_2BYTE_KIND:
13489 {
13490 _PyUnicode_CONVERT_BYTES(
13491 Py_UCS1, Py_UCS2,
13492 ascii, ascii + len,
13493 (Py_UCS2 *)writer->data + writer->pos);
13494 break;
13495 }
13496 case PyUnicode_4BYTE_KIND:
13497 {
13498 _PyUnicode_CONVERT_BYTES(
13499 Py_UCS1, Py_UCS4,
13500 ascii, ascii + len,
13501 (Py_UCS4 *)writer->data + writer->pos);
13502 break;
13503 }
13504 default:
13505 assert(0);
13506 }
13507
13508 writer->pos += len;
13509 return 0;
13510}
13511
13512int
13513_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13514 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013515{
13516 Py_UCS4 maxchar;
13517
13518 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13519 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13520 return -1;
13521 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13522 writer->pos += len;
13523 return 0;
13524}
13525
Victor Stinnerd3f08822012-05-29 12:57:52 +020013526PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013527_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013528{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013529 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013530 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013531 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013532 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013534 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013535 str = writer->buffer;
13536 writer->buffer = NULL;
13537 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13538 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013540 if (writer->pos == 0) {
13541 Py_CLEAR(writer->buffer);
13542
13543 /* Get the empty Unicode string singleton ('') */
13544 _Py_INCREF_UNICODE_EMPTY();
13545 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013546 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013547 else {
13548 str = writer->buffer;
13549 writer->buffer = NULL;
13550
13551 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13552 PyObject *str2;
13553 str2 = resize_compact(str, writer->pos);
13554 if (str2 == NULL)
13555 return NULL;
13556 str = str2;
13557 }
13558 }
13559
Victor Stinner15a0bd32013-07-08 22:29:55 +020013560 assert(_PyUnicode_CheckConsistency(str, 1));
13561 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013562}
13563
Victor Stinnerd3f08822012-05-29 12:57:52 +020013564void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013565_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013566{
13567 Py_CLEAR(writer->buffer);
13568}
13569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013571
13572PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013573 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013574\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013575Return a formatted version of S, using substitutions from args and kwargs.\n\
13576The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013577
Eric Smith27bbca62010-11-04 17:06:58 +000013578PyDoc_STRVAR(format_map__doc__,
13579 "S.format_map(mapping) -> str\n\
13580\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013581Return a formatted version of S, using substitutions from mapping.\n\
13582The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013583
Eric Smith4a7d76d2008-05-30 18:10:19 +000013584static PyObject *
13585unicode__format__(PyObject* self, PyObject* args)
13586{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013587 PyObject *format_spec;
13588 _PyUnicodeWriter writer;
13589 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013590
13591 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13592 return NULL;
13593
Victor Stinnerd3f08822012-05-29 12:57:52 +020013594 if (PyUnicode_READY(self) == -1)
13595 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013596 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013597 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13598 self, format_spec, 0,
13599 PyUnicode_GET_LENGTH(format_spec));
13600 if (ret == -1) {
13601 _PyUnicodeWriter_Dealloc(&writer);
13602 return NULL;
13603 }
13604 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013605}
13606
Eric Smith8c663262007-08-25 02:26:07 +000013607PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013608 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013609\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013610Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013611
13612static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013613unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 Py_ssize_t size;
13616
13617 /* If it's a compact object, account for base structure +
13618 character data. */
13619 if (PyUnicode_IS_COMPACT_ASCII(v))
13620 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13621 else if (PyUnicode_IS_COMPACT(v))
13622 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013623 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 else {
13625 /* If it is a two-block object, account for base object, and
13626 for character block if present. */
13627 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013628 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013630 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013631 }
13632 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013633 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013634 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013636 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013637 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638
13639 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013640}
13641
13642PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013643 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013644
13645static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013646unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013647{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013648 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013649 if (!copy)
13650 return NULL;
13651 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013652}
13653
Guido van Rossumd57fd912000-03-10 22:53:23 +000013654static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013655 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013656 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013657 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13658 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013659 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13660 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013661 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013662 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13663 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13664 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013665 {"expandtabs", (PyCFunction) unicode_expandtabs,
13666 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013667 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013668 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013669 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13670 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13671 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013672 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013673 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13674 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13675 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013676 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013677 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013678 {"splitlines", (PyCFunction) unicode_splitlines,
13679 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013680 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013681 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13682 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13683 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13684 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13685 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13686 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13687 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13688 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13689 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13690 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13691 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13692 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13693 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13694 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013695 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013696 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013697 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013698 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013699 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013700 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013701 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013702 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013703#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013704 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013705 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013706#endif
13707
Benjamin Peterson14339b62009-01-31 16:36:08 +000013708 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013709 {NULL, NULL}
13710};
13711
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013712static PyObject *
13713unicode_mod(PyObject *v, PyObject *w)
13714{
Brian Curtindfc80e32011-08-10 20:28:54 -050013715 if (!PyUnicode_Check(v))
13716 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013717 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013718}
13719
13720static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013721 0, /*nb_add*/
13722 0, /*nb_subtract*/
13723 0, /*nb_multiply*/
13724 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013725};
13726
Guido van Rossumd57fd912000-03-10 22:53:23 +000013727static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013728 (lenfunc) unicode_length, /* sq_length */
13729 PyUnicode_Concat, /* sq_concat */
13730 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13731 (ssizeargfunc) unicode_getitem, /* sq_item */
13732 0, /* sq_slice */
13733 0, /* sq_ass_item */
13734 0, /* sq_ass_slice */
13735 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013736};
13737
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013738static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013739unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013740{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013741 if (PyUnicode_READY(self) == -1)
13742 return NULL;
13743
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013744 if (PyIndex_Check(item)) {
13745 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013746 if (i == -1 && PyErr_Occurred())
13747 return NULL;
13748 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013749 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013750 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013751 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013752 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013753 PyObject *result;
13754 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013755 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013756 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013758 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013759 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013760 return NULL;
13761 }
13762
13763 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013764 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013765 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013766 slicelength == PyUnicode_GET_LENGTH(self)) {
13767 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013768 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013769 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013770 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013771 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013772 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013773 src_kind = PyUnicode_KIND(self);
13774 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013775 if (!PyUnicode_IS_ASCII(self)) {
13776 kind_limit = kind_maxchar_limit(src_kind);
13777 max_char = 0;
13778 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13779 ch = PyUnicode_READ(src_kind, src_data, cur);
13780 if (ch > max_char) {
13781 max_char = ch;
13782 if (max_char >= kind_limit)
13783 break;
13784 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013785 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013786 }
Victor Stinner55c99112011-10-13 01:17:06 +020013787 else
13788 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013789 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013790 if (result == NULL)
13791 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013792 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013793 dest_data = PyUnicode_DATA(result);
13794
13795 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013796 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13797 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013798 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013799 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013800 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013801 } else {
13802 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13803 return NULL;
13804 }
13805}
13806
13807static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013808 (lenfunc)unicode_length, /* mp_length */
13809 (binaryfunc)unicode_subscript, /* mp_subscript */
13810 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013811};
13812
Guido van Rossumd57fd912000-03-10 22:53:23 +000013813
Guido van Rossumd57fd912000-03-10 22:53:23 +000013814/* Helpers for PyUnicode_Format() */
13815
Victor Stinnera47082312012-10-04 02:19:54 +020013816struct unicode_formatter_t {
13817 PyObject *args;
13818 int args_owned;
13819 Py_ssize_t arglen, argidx;
13820 PyObject *dict;
13821
13822 enum PyUnicode_Kind fmtkind;
13823 Py_ssize_t fmtcnt, fmtpos;
13824 void *fmtdata;
13825 PyObject *fmtstr;
13826
13827 _PyUnicodeWriter writer;
13828};
13829
13830struct unicode_format_arg_t {
13831 Py_UCS4 ch;
13832 int flags;
13833 Py_ssize_t width;
13834 int prec;
13835 int sign;
13836};
13837
Guido van Rossumd57fd912000-03-10 22:53:23 +000013838static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013839unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013840{
Victor Stinnera47082312012-10-04 02:19:54 +020013841 Py_ssize_t argidx = ctx->argidx;
13842
13843 if (argidx < ctx->arglen) {
13844 ctx->argidx++;
13845 if (ctx->arglen < 0)
13846 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013847 else
Victor Stinnera47082312012-10-04 02:19:54 +020013848 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013849 }
13850 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013851 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013852 return NULL;
13853}
13854
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013855/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013856
Victor Stinnera47082312012-10-04 02:19:54 +020013857/* Format a float into the writer if the writer is not NULL, or into *p_output
13858 otherwise.
13859
13860 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013861static int
Victor Stinnera47082312012-10-04 02:19:54 +020013862formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13863 PyObject **p_output,
13864 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013865{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013866 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013867 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013868 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013869 int prec;
13870 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013871
Guido van Rossumd57fd912000-03-10 22:53:23 +000013872 x = PyFloat_AsDouble(v);
13873 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013874 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013875
Victor Stinnera47082312012-10-04 02:19:54 +020013876 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013877 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013878 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013879
Victor Stinnera47082312012-10-04 02:19:54 +020013880 if (arg->flags & F_ALT)
13881 dtoa_flags = Py_DTSF_ALT;
13882 else
13883 dtoa_flags = 0;
13884 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013885 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013886 return -1;
13887 len = strlen(p);
13888 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013889 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013890 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013891 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013892 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013893 }
13894 else
13895 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013896 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013897 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013898}
13899
Victor Stinnerd0880d52012-04-27 23:40:13 +020013900/* formatlong() emulates the format codes d, u, o, x and X, and
13901 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13902 * Python's regular ints.
13903 * Return value: a new PyUnicodeObject*, or NULL if error.
13904 * The output string is of the form
13905 * "-"? ("0x" | "0X")? digit+
13906 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13907 * set in flags. The case of hex digits will be correct,
13908 * There will be at least prec digits, zero-filled on the left if
13909 * necessary to get that many.
13910 * val object to be converted
13911 * flags bitmask of format flags; only F_ALT is looked at
13912 * prec minimum number of digits; 0-fill on left if needed
13913 * type a character in [duoxX]; u acts the same as d
13914 *
13915 * CAUTION: o, x and X conversions on regular ints can never
13916 * produce a '-' sign, but can for Python's unbounded ints.
13917 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013918PyObject *
13919_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013920{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013921 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013922 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013923 Py_ssize_t i;
13924 int sign; /* 1 if '-', else 0 */
13925 int len; /* number of characters */
13926 Py_ssize_t llen;
13927 int numdigits; /* len == numnondigits + numdigits */
13928 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013929
Victor Stinnerd0880d52012-04-27 23:40:13 +020013930 /* Avoid exceeding SSIZE_T_MAX */
13931 if (prec > INT_MAX-3) {
13932 PyErr_SetString(PyExc_OverflowError,
13933 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013934 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013935 }
13936
13937 assert(PyLong_Check(val));
13938
13939 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013940 default:
13941 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013942 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013943 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013944 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013945 /* int and int subclasses should print numerically when a numeric */
13946 /* format code is used (see issue18780) */
13947 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013948 break;
13949 case 'o':
13950 numnondigits = 2;
13951 result = PyNumber_ToBase(val, 8);
13952 break;
13953 case 'x':
13954 case 'X':
13955 numnondigits = 2;
13956 result = PyNumber_ToBase(val, 16);
13957 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013958 }
13959 if (!result)
13960 return NULL;
13961
13962 assert(unicode_modifiable(result));
13963 assert(PyUnicode_IS_READY(result));
13964 assert(PyUnicode_IS_ASCII(result));
13965
13966 /* To modify the string in-place, there can only be one reference. */
13967 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013968 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013969 PyErr_BadInternalCall();
13970 return NULL;
13971 }
13972 buf = PyUnicode_DATA(result);
13973 llen = PyUnicode_GET_LENGTH(result);
13974 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013975 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013976 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013977 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013978 return NULL;
13979 }
13980 len = (int)llen;
13981 sign = buf[0] == '-';
13982 numnondigits += sign;
13983 numdigits = len - numnondigits;
13984 assert(numdigits > 0);
13985
13986 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013987 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013988 (type == 'o' || type == 'x' || type == 'X'))) {
13989 assert(buf[sign] == '0');
13990 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13991 buf[sign+1] == 'o');
13992 numnondigits -= 2;
13993 buf += 2;
13994 len -= 2;
13995 if (sign)
13996 buf[0] = '-';
13997 assert(len == numnondigits + numdigits);
13998 assert(numdigits > 0);
13999 }
14000
14001 /* Fill with leading zeroes to meet minimum width. */
14002 if (prec > numdigits) {
14003 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14004 numnondigits + prec);
14005 char *b1;
14006 if (!r1) {
14007 Py_DECREF(result);
14008 return NULL;
14009 }
14010 b1 = PyBytes_AS_STRING(r1);
14011 for (i = 0; i < numnondigits; ++i)
14012 *b1++ = *buf++;
14013 for (i = 0; i < prec - numdigits; i++)
14014 *b1++ = '0';
14015 for (i = 0; i < numdigits; i++)
14016 *b1++ = *buf++;
14017 *b1 = '\0';
14018 Py_DECREF(result);
14019 result = r1;
14020 buf = PyBytes_AS_STRING(result);
14021 len = numnondigits + prec;
14022 }
14023
14024 /* Fix up case for hex conversions. */
14025 if (type == 'X') {
14026 /* Need to convert all lower case letters to upper case.
14027 and need to convert 0x to 0X (and -0x to -0X). */
14028 for (i = 0; i < len; i++)
14029 if (buf[i] >= 'a' && buf[i] <= 'x')
14030 buf[i] -= 'a'-'A';
14031 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014032 if (!PyUnicode_Check(result)
14033 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014034 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014035 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014036 Py_DECREF(result);
14037 result = unicode;
14038 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014039 else if (len != PyUnicode_GET_LENGTH(result)) {
14040 if (PyUnicode_Resize(&result, len) < 0)
14041 Py_CLEAR(result);
14042 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014044}
14045
Ethan Furmandf3ed242014-01-05 06:50:30 -080014046/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014047 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014048 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014049 * -1 and raise an exception on error */
14050static int
Victor Stinnera47082312012-10-04 02:19:54 +020014051mainformatlong(PyObject *v,
14052 struct unicode_format_arg_t *arg,
14053 PyObject **p_output,
14054 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014055{
14056 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014057 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014058
14059 if (!PyNumber_Check(v))
14060 goto wrongtype;
14061
Ethan Furman9ab74802014-03-21 06:38:46 -070014062 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014063 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014064 if (type == 'o' || type == 'x' || type == 'X') {
14065 iobj = PyNumber_Index(v);
14066 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014067 if (PyErr_ExceptionMatches(PyExc_TypeError))
14068 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014069 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014070 }
14071 }
14072 else {
14073 iobj = PyNumber_Long(v);
14074 if (iobj == NULL ) {
14075 if (PyErr_ExceptionMatches(PyExc_TypeError))
14076 goto wrongtype;
14077 return -1;
14078 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014079 }
14080 assert(PyLong_Check(iobj));
14081 }
14082 else {
14083 iobj = v;
14084 Py_INCREF(iobj);
14085 }
14086
14087 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014088 && arg->width == -1 && arg->prec == -1
14089 && !(arg->flags & (F_SIGN | F_BLANK))
14090 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014091 {
14092 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014093 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014094 int base;
14095
Victor Stinnera47082312012-10-04 02:19:54 +020014096 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014097 {
14098 default:
14099 assert(0 && "'type' not in [diuoxX]");
14100 case 'd':
14101 case 'i':
14102 case 'u':
14103 base = 10;
14104 break;
14105 case 'o':
14106 base = 8;
14107 break;
14108 case 'x':
14109 case 'X':
14110 base = 16;
14111 break;
14112 }
14113
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014114 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14115 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014116 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014117 }
14118 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014119 return 1;
14120 }
14121
Ethan Furmanb95b5612015-01-23 20:05:18 -080014122 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014123 Py_DECREF(iobj);
14124 if (res == NULL)
14125 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014126 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014127 return 0;
14128
14129wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014130 switch(type)
14131 {
14132 case 'o':
14133 case 'x':
14134 case 'X':
14135 PyErr_Format(PyExc_TypeError,
14136 "%%%c format: an integer is required, "
14137 "not %.200s",
14138 type, Py_TYPE(v)->tp_name);
14139 break;
14140 default:
14141 PyErr_Format(PyExc_TypeError,
14142 "%%%c format: a number is required, "
14143 "not %.200s",
14144 type, Py_TYPE(v)->tp_name);
14145 break;
14146 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014147 return -1;
14148}
14149
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014150static Py_UCS4
14151formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014152{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014153 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014154 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014155 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014156 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014157 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014158 goto onError;
14159 }
14160 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014161 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014162 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014163 /* make sure number is a type of integer */
14164 if (!PyLong_Check(v)) {
14165 iobj = PyNumber_Index(v);
14166 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014167 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014168 }
14169 v = iobj;
14170 Py_DECREF(iobj);
14171 }
14172 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014173 x = PyLong_AsLong(v);
14174 if (x == -1 && PyErr_Occurred())
14175 goto onError;
14176
Victor Stinner8faf8212011-12-08 22:14:11 +010014177 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014178 PyErr_SetString(PyExc_OverflowError,
14179 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014180 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014181 }
14182
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014183 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014184 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014185
Benjamin Peterson29060642009-01-31 22:14:21 +000014186 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014187 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014188 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014189 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014190}
14191
Victor Stinnera47082312012-10-04 02:19:54 +020014192/* Parse options of an argument: flags, width, precision.
14193 Handle also "%(name)" syntax.
14194
14195 Return 0 if the argument has been formatted into arg->str.
14196 Return 1 if the argument has been written into ctx->writer,
14197 Raise an exception and return -1 on error. */
14198static int
14199unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14200 struct unicode_format_arg_t *arg)
14201{
14202#define FORMAT_READ(ctx) \
14203 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14204
14205 PyObject *v;
14206
Victor Stinnera47082312012-10-04 02:19:54 +020014207 if (arg->ch == '(') {
14208 /* Get argument value from a dictionary. Example: "%(name)s". */
14209 Py_ssize_t keystart;
14210 Py_ssize_t keylen;
14211 PyObject *key;
14212 int pcount = 1;
14213
14214 if (ctx->dict == NULL) {
14215 PyErr_SetString(PyExc_TypeError,
14216 "format requires a mapping");
14217 return -1;
14218 }
14219 ++ctx->fmtpos;
14220 --ctx->fmtcnt;
14221 keystart = ctx->fmtpos;
14222 /* Skip over balanced parentheses */
14223 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14224 arg->ch = FORMAT_READ(ctx);
14225 if (arg->ch == ')')
14226 --pcount;
14227 else if (arg->ch == '(')
14228 ++pcount;
14229 ctx->fmtpos++;
14230 }
14231 keylen = ctx->fmtpos - keystart - 1;
14232 if (ctx->fmtcnt < 0 || pcount > 0) {
14233 PyErr_SetString(PyExc_ValueError,
14234 "incomplete format key");
14235 return -1;
14236 }
14237 key = PyUnicode_Substring(ctx->fmtstr,
14238 keystart, keystart + keylen);
14239 if (key == NULL)
14240 return -1;
14241 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014242 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014243 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014244 }
14245 ctx->args = PyObject_GetItem(ctx->dict, key);
14246 Py_DECREF(key);
14247 if (ctx->args == NULL)
14248 return -1;
14249 ctx->args_owned = 1;
14250 ctx->arglen = -1;
14251 ctx->argidx = -2;
14252 }
14253
14254 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014255 while (--ctx->fmtcnt >= 0) {
14256 arg->ch = FORMAT_READ(ctx);
14257 ctx->fmtpos++;
14258 switch (arg->ch) {
14259 case '-': arg->flags |= F_LJUST; continue;
14260 case '+': arg->flags |= F_SIGN; continue;
14261 case ' ': arg->flags |= F_BLANK; continue;
14262 case '#': arg->flags |= F_ALT; continue;
14263 case '0': arg->flags |= F_ZERO; continue;
14264 }
14265 break;
14266 }
14267
14268 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014269 if (arg->ch == '*') {
14270 v = unicode_format_getnextarg(ctx);
14271 if (v == NULL)
14272 return -1;
14273 if (!PyLong_Check(v)) {
14274 PyErr_SetString(PyExc_TypeError,
14275 "* wants int");
14276 return -1;
14277 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014278 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014279 if (arg->width == -1 && PyErr_Occurred())
14280 return -1;
14281 if (arg->width < 0) {
14282 arg->flags |= F_LJUST;
14283 arg->width = -arg->width;
14284 }
14285 if (--ctx->fmtcnt >= 0) {
14286 arg->ch = FORMAT_READ(ctx);
14287 ctx->fmtpos++;
14288 }
14289 }
14290 else if (arg->ch >= '0' && arg->ch <= '9') {
14291 arg->width = arg->ch - '0';
14292 while (--ctx->fmtcnt >= 0) {
14293 arg->ch = FORMAT_READ(ctx);
14294 ctx->fmtpos++;
14295 if (arg->ch < '0' || arg->ch > '9')
14296 break;
14297 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14298 mixing signed and unsigned comparison. Since arg->ch is between
14299 '0' and '9', casting to int is safe. */
14300 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14301 PyErr_SetString(PyExc_ValueError,
14302 "width too big");
14303 return -1;
14304 }
14305 arg->width = arg->width*10 + (arg->ch - '0');
14306 }
14307 }
14308
14309 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014310 if (arg->ch == '.') {
14311 arg->prec = 0;
14312 if (--ctx->fmtcnt >= 0) {
14313 arg->ch = FORMAT_READ(ctx);
14314 ctx->fmtpos++;
14315 }
14316 if (arg->ch == '*') {
14317 v = unicode_format_getnextarg(ctx);
14318 if (v == NULL)
14319 return -1;
14320 if (!PyLong_Check(v)) {
14321 PyErr_SetString(PyExc_TypeError,
14322 "* wants int");
14323 return -1;
14324 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014325 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014326 if (arg->prec == -1 && PyErr_Occurred())
14327 return -1;
14328 if (arg->prec < 0)
14329 arg->prec = 0;
14330 if (--ctx->fmtcnt >= 0) {
14331 arg->ch = FORMAT_READ(ctx);
14332 ctx->fmtpos++;
14333 }
14334 }
14335 else if (arg->ch >= '0' && arg->ch <= '9') {
14336 arg->prec = arg->ch - '0';
14337 while (--ctx->fmtcnt >= 0) {
14338 arg->ch = FORMAT_READ(ctx);
14339 ctx->fmtpos++;
14340 if (arg->ch < '0' || arg->ch > '9')
14341 break;
14342 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14343 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014344 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014345 return -1;
14346 }
14347 arg->prec = arg->prec*10 + (arg->ch - '0');
14348 }
14349 }
14350 }
14351
14352 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14353 if (ctx->fmtcnt >= 0) {
14354 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14355 if (--ctx->fmtcnt >= 0) {
14356 arg->ch = FORMAT_READ(ctx);
14357 ctx->fmtpos++;
14358 }
14359 }
14360 }
14361 if (ctx->fmtcnt < 0) {
14362 PyErr_SetString(PyExc_ValueError,
14363 "incomplete format");
14364 return -1;
14365 }
14366 return 0;
14367
14368#undef FORMAT_READ
14369}
14370
14371/* Format one argument. Supported conversion specifiers:
14372
14373 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014374 - "i", "d", "u": int or float
14375 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014376 - "e", "E", "f", "F", "g", "G": float
14377 - "c": int or str (1 character)
14378
Victor Stinner8dbd4212012-12-04 09:30:24 +010014379 When possible, the output is written directly into the Unicode writer
14380 (ctx->writer). A string is created when padding is required.
14381
Victor Stinnera47082312012-10-04 02:19:54 +020014382 Return 0 if the argument has been formatted into *p_str,
14383 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014384 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014385static int
14386unicode_format_arg_format(struct unicode_formatter_t *ctx,
14387 struct unicode_format_arg_t *arg,
14388 PyObject **p_str)
14389{
14390 PyObject *v;
14391 _PyUnicodeWriter *writer = &ctx->writer;
14392
14393 if (ctx->fmtcnt == 0)
14394 ctx->writer.overallocate = 0;
14395
14396 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014397 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014398 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014399 return 1;
14400 }
14401
14402 v = unicode_format_getnextarg(ctx);
14403 if (v == NULL)
14404 return -1;
14405
Victor Stinnera47082312012-10-04 02:19:54 +020014406
14407 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014408 case 's':
14409 case 'r':
14410 case 'a':
14411 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14412 /* Fast path */
14413 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14414 return -1;
14415 return 1;
14416 }
14417
14418 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14419 *p_str = v;
14420 Py_INCREF(*p_str);
14421 }
14422 else {
14423 if (arg->ch == 's')
14424 *p_str = PyObject_Str(v);
14425 else if (arg->ch == 'r')
14426 *p_str = PyObject_Repr(v);
14427 else
14428 *p_str = PyObject_ASCII(v);
14429 }
14430 break;
14431
14432 case 'i':
14433 case 'd':
14434 case 'u':
14435 case 'o':
14436 case 'x':
14437 case 'X':
14438 {
14439 int ret = mainformatlong(v, arg, p_str, writer);
14440 if (ret != 0)
14441 return ret;
14442 arg->sign = 1;
14443 break;
14444 }
14445
14446 case 'e':
14447 case 'E':
14448 case 'f':
14449 case 'F':
14450 case 'g':
14451 case 'G':
14452 if (arg->width == -1 && arg->prec == -1
14453 && !(arg->flags & (F_SIGN | F_BLANK)))
14454 {
14455 /* Fast path */
14456 if (formatfloat(v, arg, NULL, writer) == -1)
14457 return -1;
14458 return 1;
14459 }
14460
14461 arg->sign = 1;
14462 if (formatfloat(v, arg, p_str, NULL) == -1)
14463 return -1;
14464 break;
14465
14466 case 'c':
14467 {
14468 Py_UCS4 ch = formatchar(v);
14469 if (ch == (Py_UCS4) -1)
14470 return -1;
14471 if (arg->width == -1 && arg->prec == -1) {
14472 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014473 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014474 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014475 return 1;
14476 }
14477 *p_str = PyUnicode_FromOrdinal(ch);
14478 break;
14479 }
14480
14481 default:
14482 PyErr_Format(PyExc_ValueError,
14483 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014484 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014485 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14486 (int)arg->ch,
14487 ctx->fmtpos - 1);
14488 return -1;
14489 }
14490 if (*p_str == NULL)
14491 return -1;
14492 assert (PyUnicode_Check(*p_str));
14493 return 0;
14494}
14495
14496static int
14497unicode_format_arg_output(struct unicode_formatter_t *ctx,
14498 struct unicode_format_arg_t *arg,
14499 PyObject *str)
14500{
14501 Py_ssize_t len;
14502 enum PyUnicode_Kind kind;
14503 void *pbuf;
14504 Py_ssize_t pindex;
14505 Py_UCS4 signchar;
14506 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014507 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014508 Py_ssize_t sublen;
14509 _PyUnicodeWriter *writer = &ctx->writer;
14510 Py_UCS4 fill;
14511
14512 fill = ' ';
14513 if (arg->sign && arg->flags & F_ZERO)
14514 fill = '0';
14515
14516 if (PyUnicode_READY(str) == -1)
14517 return -1;
14518
14519 len = PyUnicode_GET_LENGTH(str);
14520 if ((arg->width == -1 || arg->width <= len)
14521 && (arg->prec == -1 || arg->prec >= len)
14522 && !(arg->flags & (F_SIGN | F_BLANK)))
14523 {
14524 /* Fast path */
14525 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14526 return -1;
14527 return 0;
14528 }
14529
14530 /* Truncate the string for "s", "r" and "a" formats
14531 if the precision is set */
14532 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14533 if (arg->prec >= 0 && len > arg->prec)
14534 len = arg->prec;
14535 }
14536
14537 /* Adjust sign and width */
14538 kind = PyUnicode_KIND(str);
14539 pbuf = PyUnicode_DATA(str);
14540 pindex = 0;
14541 signchar = '\0';
14542 if (arg->sign) {
14543 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14544 if (ch == '-' || ch == '+') {
14545 signchar = ch;
14546 len--;
14547 pindex++;
14548 }
14549 else if (arg->flags & F_SIGN)
14550 signchar = '+';
14551 else if (arg->flags & F_BLANK)
14552 signchar = ' ';
14553 else
14554 arg->sign = 0;
14555 }
14556 if (arg->width < len)
14557 arg->width = len;
14558
14559 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014560 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014561 if (!(arg->flags & F_LJUST)) {
14562 if (arg->sign) {
14563 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014564 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014565 }
14566 else {
14567 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014568 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014569 }
14570 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014571 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14572 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014573 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014574 }
14575
Victor Stinnera47082312012-10-04 02:19:54 +020014576 buflen = arg->width;
14577 if (arg->sign && len == arg->width)
14578 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014579 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014580 return -1;
14581
14582 /* Write the sign if needed */
14583 if (arg->sign) {
14584 if (fill != ' ') {
14585 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14586 writer->pos += 1;
14587 }
14588 if (arg->width > len)
14589 arg->width--;
14590 }
14591
14592 /* Write the numeric prefix for "x", "X" and "o" formats
14593 if the alternate form is used.
14594 For example, write "0x" for the "%#x" format. */
14595 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14596 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14597 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14598 if (fill != ' ') {
14599 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14600 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14601 writer->pos += 2;
14602 pindex += 2;
14603 }
14604 arg->width -= 2;
14605 if (arg->width < 0)
14606 arg->width = 0;
14607 len -= 2;
14608 }
14609
14610 /* Pad left with the fill character if needed */
14611 if (arg->width > len && !(arg->flags & F_LJUST)) {
14612 sublen = arg->width - len;
14613 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14614 writer->pos += sublen;
14615 arg->width = len;
14616 }
14617
14618 /* If padding with spaces: write sign if needed and/or numeric prefix if
14619 the alternate form is used */
14620 if (fill == ' ') {
14621 if (arg->sign) {
14622 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14623 writer->pos += 1;
14624 }
14625 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14626 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14627 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14628 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14629 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14630 writer->pos += 2;
14631 pindex += 2;
14632 }
14633 }
14634
14635 /* Write characters */
14636 if (len) {
14637 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14638 str, pindex, len);
14639 writer->pos += len;
14640 }
14641
14642 /* Pad right with the fill character if needed */
14643 if (arg->width > len) {
14644 sublen = arg->width - len;
14645 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14646 writer->pos += sublen;
14647 }
14648 return 0;
14649}
14650
14651/* Helper of PyUnicode_Format(): format one arg.
14652 Return 0 on success, raise an exception and return -1 on error. */
14653static int
14654unicode_format_arg(struct unicode_formatter_t *ctx)
14655{
14656 struct unicode_format_arg_t arg;
14657 PyObject *str;
14658 int ret;
14659
Victor Stinner8dbd4212012-12-04 09:30:24 +010014660 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14661 arg.flags = 0;
14662 arg.width = -1;
14663 arg.prec = -1;
14664 arg.sign = 0;
14665 str = NULL;
14666
Victor Stinnera47082312012-10-04 02:19:54 +020014667 ret = unicode_format_arg_parse(ctx, &arg);
14668 if (ret == -1)
14669 return -1;
14670
14671 ret = unicode_format_arg_format(ctx, &arg, &str);
14672 if (ret == -1)
14673 return -1;
14674
14675 if (ret != 1) {
14676 ret = unicode_format_arg_output(ctx, &arg, str);
14677 Py_DECREF(str);
14678 if (ret == -1)
14679 return -1;
14680 }
14681
14682 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14683 PyErr_SetString(PyExc_TypeError,
14684 "not all arguments converted during string formatting");
14685 return -1;
14686 }
14687 return 0;
14688}
14689
Alexander Belopolsky40018472011-02-26 01:02:56 +000014690PyObject *
14691PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014692{
Victor Stinnera47082312012-10-04 02:19:54 +020014693 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014694
Guido van Rossumd57fd912000-03-10 22:53:23 +000014695 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014696 PyErr_BadInternalCall();
14697 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014698 }
Victor Stinnera47082312012-10-04 02:19:54 +020014699
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014700 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014701 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014702
14703 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014704 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14705 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14706 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14707 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014708
Victor Stinner8f674cc2013-04-17 23:02:17 +020014709 _PyUnicodeWriter_Init(&ctx.writer);
14710 ctx.writer.min_length = ctx.fmtcnt + 100;
14711 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014712
Guido van Rossumd57fd912000-03-10 22:53:23 +000014713 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014714 ctx.arglen = PyTuple_Size(args);
14715 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014716 }
14717 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014718 ctx.arglen = -1;
14719 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014720 }
Victor Stinnera47082312012-10-04 02:19:54 +020014721 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014722 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014723 ctx.dict = args;
14724 else
14725 ctx.dict = NULL;
14726 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014727
Victor Stinnera47082312012-10-04 02:19:54 +020014728 while (--ctx.fmtcnt >= 0) {
14729 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014730 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014731
14732 nonfmtpos = ctx.fmtpos++;
14733 while (ctx.fmtcnt >= 0 &&
14734 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14735 ctx.fmtpos++;
14736 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014737 }
Victor Stinnera47082312012-10-04 02:19:54 +020014738 if (ctx.fmtcnt < 0) {
14739 ctx.fmtpos--;
14740 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014741 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014742
Victor Stinnercfc4c132013-04-03 01:48:39 +020014743 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14744 nonfmtpos, ctx.fmtpos) < 0)
14745 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014746 }
14747 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014748 ctx.fmtpos++;
14749 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014750 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014751 }
14752 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014753
Victor Stinnera47082312012-10-04 02:19:54 +020014754 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014755 PyErr_SetString(PyExc_TypeError,
14756 "not all arguments converted during string formatting");
14757 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014758 }
14759
Victor Stinnera47082312012-10-04 02:19:54 +020014760 if (ctx.args_owned) {
14761 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014762 }
Victor Stinnera47082312012-10-04 02:19:54 +020014763 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014764
Benjamin Peterson29060642009-01-31 22:14:21 +000014765 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014766 _PyUnicodeWriter_Dealloc(&ctx.writer);
14767 if (ctx.args_owned) {
14768 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014769 }
14770 return NULL;
14771}
14772
Jeremy Hylton938ace62002-07-17 16:30:39 +000014773static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014774unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14775
Tim Peters6d6c1a32001-08-02 04:15:00 +000014776static PyObject *
14777unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14778{
Benjamin Peterson29060642009-01-31 22:14:21 +000014779 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014780 static char *kwlist[] = {"object", "encoding", "errors", 0};
14781 char *encoding = NULL;
14782 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014783
Benjamin Peterson14339b62009-01-31 16:36:08 +000014784 if (type != &PyUnicode_Type)
14785 return unicode_subtype_new(type, args, kwds);
14786 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014787 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014788 return NULL;
14789 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014790 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014791 if (encoding == NULL && errors == NULL)
14792 return PyObject_Str(x);
14793 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014794 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014795}
14796
Guido van Rossume023fe02001-08-30 03:12:59 +000014797static PyObject *
14798unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14799{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014800 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014801 Py_ssize_t length, char_size;
14802 int share_wstr, share_utf8;
14803 unsigned int kind;
14804 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014805
Benjamin Peterson14339b62009-01-31 16:36:08 +000014806 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014807
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014808 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014809 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014810 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014811 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014812 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014813 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014814 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014815 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014816
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014817 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014818 if (self == NULL) {
14819 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014820 return NULL;
14821 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014822 kind = PyUnicode_KIND(unicode);
14823 length = PyUnicode_GET_LENGTH(unicode);
14824
14825 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014826#ifdef Py_DEBUG
14827 _PyUnicode_HASH(self) = -1;
14828#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014829 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014830#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014831 _PyUnicode_STATE(self).interned = 0;
14832 _PyUnicode_STATE(self).kind = kind;
14833 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014834 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014835 _PyUnicode_STATE(self).ready = 1;
14836 _PyUnicode_WSTR(self) = NULL;
14837 _PyUnicode_UTF8_LENGTH(self) = 0;
14838 _PyUnicode_UTF8(self) = NULL;
14839 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014840 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014841
14842 share_utf8 = 0;
14843 share_wstr = 0;
14844 if (kind == PyUnicode_1BYTE_KIND) {
14845 char_size = 1;
14846 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14847 share_utf8 = 1;
14848 }
14849 else if (kind == PyUnicode_2BYTE_KIND) {
14850 char_size = 2;
14851 if (sizeof(wchar_t) == 2)
14852 share_wstr = 1;
14853 }
14854 else {
14855 assert(kind == PyUnicode_4BYTE_KIND);
14856 char_size = 4;
14857 if (sizeof(wchar_t) == 4)
14858 share_wstr = 1;
14859 }
14860
14861 /* Ensure we won't overflow the length. */
14862 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14863 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014864 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014865 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014866 data = PyObject_MALLOC((length + 1) * char_size);
14867 if (data == NULL) {
14868 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014869 goto onError;
14870 }
14871
Victor Stinnerc3c74152011-10-02 20:39:55 +020014872 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014873 if (share_utf8) {
14874 _PyUnicode_UTF8_LENGTH(self) = length;
14875 _PyUnicode_UTF8(self) = data;
14876 }
14877 if (share_wstr) {
14878 _PyUnicode_WSTR_LENGTH(self) = length;
14879 _PyUnicode_WSTR(self) = (wchar_t *)data;
14880 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014881
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014882 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014883 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014884 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014885#ifdef Py_DEBUG
14886 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14887#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014888 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014889 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014890
14891onError:
14892 Py_DECREF(unicode);
14893 Py_DECREF(self);
14894 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014895}
14896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014897PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014898"str(object='') -> str\n\
14899str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014900\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014901Create a new string object from the given object. If encoding or\n\
14902errors is specified, then the object must expose a data buffer\n\
14903that will be decoded using the given encoding and error handler.\n\
14904Otherwise, returns the result of object.__str__() (if defined)\n\
14905or repr(object).\n\
14906encoding defaults to sys.getdefaultencoding().\n\
14907errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014908
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014909static PyObject *unicode_iter(PyObject *seq);
14910
Guido van Rossumd57fd912000-03-10 22:53:23 +000014911PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014912 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014913 "str", /* tp_name */
14914 sizeof(PyUnicodeObject), /* tp_size */
14915 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014916 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014917 (destructor)unicode_dealloc, /* tp_dealloc */
14918 0, /* tp_print */
14919 0, /* tp_getattr */
14920 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014921 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014922 unicode_repr, /* tp_repr */
14923 &unicode_as_number, /* tp_as_number */
14924 &unicode_as_sequence, /* tp_as_sequence */
14925 &unicode_as_mapping, /* tp_as_mapping */
14926 (hashfunc) unicode_hash, /* tp_hash*/
14927 0, /* tp_call*/
14928 (reprfunc) unicode_str, /* tp_str */
14929 PyObject_GenericGetAttr, /* tp_getattro */
14930 0, /* tp_setattro */
14931 0, /* tp_as_buffer */
14932 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014933 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014934 unicode_doc, /* tp_doc */
14935 0, /* tp_traverse */
14936 0, /* tp_clear */
14937 PyUnicode_RichCompare, /* tp_richcompare */
14938 0, /* tp_weaklistoffset */
14939 unicode_iter, /* tp_iter */
14940 0, /* tp_iternext */
14941 unicode_methods, /* tp_methods */
14942 0, /* tp_members */
14943 0, /* tp_getset */
14944 &PyBaseObject_Type, /* tp_base */
14945 0, /* tp_dict */
14946 0, /* tp_descr_get */
14947 0, /* tp_descr_set */
14948 0, /* tp_dictoffset */
14949 0, /* tp_init */
14950 0, /* tp_alloc */
14951 unicode_new, /* tp_new */
14952 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014953};
14954
14955/* Initialize the Unicode implementation */
14956
Victor Stinner3a50e702011-10-18 21:21:00 +020014957int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014958{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014959 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014960 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014961 0x000A, /* LINE FEED */
14962 0x000D, /* CARRIAGE RETURN */
14963 0x001C, /* FILE SEPARATOR */
14964 0x001D, /* GROUP SEPARATOR */
14965 0x001E, /* RECORD SEPARATOR */
14966 0x0085, /* NEXT LINE */
14967 0x2028, /* LINE SEPARATOR */
14968 0x2029, /* PARAGRAPH SEPARATOR */
14969 };
14970
Fred Drakee4315f52000-05-09 19:53:39 +000014971 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014972 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014973 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014974 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014975 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014976
Guido van Rossumcacfc072002-05-24 19:01:59 +000014977 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014978 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014979
14980 /* initialize the linebreak bloom filter */
14981 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014982 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014983 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014984
Christian Heimes26532f72013-07-20 14:57:16 +020014985 if (PyType_Ready(&EncodingMapType) < 0)
14986 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014987
Benjamin Petersonc4311282012-10-30 23:21:10 -040014988 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14989 Py_FatalError("Can't initialize field name iterator type");
14990
14991 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14992 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014993
Victor Stinner3a50e702011-10-18 21:21:00 +020014994 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014995}
14996
14997/* Finalize the Unicode implementation */
14998
Christian Heimesa156e092008-02-16 07:38:31 +000014999int
15000PyUnicode_ClearFreeList(void)
15001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015002 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015003}
15004
Guido van Rossumd57fd912000-03-10 22:53:23 +000015005void
Thomas Wouters78890102000-07-22 19:25:51 +000015006_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015007{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015008 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015009
Serhiy Storchaka05997252013-01-26 12:14:02 +020015010 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015011
Serhiy Storchaka05997252013-01-26 12:14:02 +020015012 for (i = 0; i < 256; i++)
15013 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015014 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015015 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015016}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015017
Walter Dörwald16807132007-05-25 13:52:07 +000015018void
15019PyUnicode_InternInPlace(PyObject **p)
15020{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015021 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015022 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015023#ifdef Py_DEBUG
15024 assert(s != NULL);
15025 assert(_PyUnicode_CHECK(s));
15026#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015027 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015028 return;
15029#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015030 /* If it's a subclass, we don't really know what putting
15031 it in the interned dict might do. */
15032 if (!PyUnicode_CheckExact(s))
15033 return;
15034 if (PyUnicode_CHECK_INTERNED(s))
15035 return;
15036 if (interned == NULL) {
15037 interned = PyDict_New();
15038 if (interned == NULL) {
15039 PyErr_Clear(); /* Don't leave an exception */
15040 return;
15041 }
15042 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015043 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015044 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015045 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015046 if (t == NULL) {
15047 PyErr_Clear();
15048 return;
15049 }
15050 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015051 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015052 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015053 return;
15054 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015055 /* The two references in interned are not counted by refcnt.
15056 The deallocator will take care of this */
15057 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015058 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015059}
15060
15061void
15062PyUnicode_InternImmortal(PyObject **p)
15063{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015064 PyUnicode_InternInPlace(p);
15065 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015066 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015067 Py_INCREF(*p);
15068 }
Walter Dörwald16807132007-05-25 13:52:07 +000015069}
15070
15071PyObject *
15072PyUnicode_InternFromString(const char *cp)
15073{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015074 PyObject *s = PyUnicode_FromString(cp);
15075 if (s == NULL)
15076 return NULL;
15077 PyUnicode_InternInPlace(&s);
15078 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015079}
15080
Alexander Belopolsky40018472011-02-26 01:02:56 +000015081void
15082_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015083{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015084 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015085 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015086 Py_ssize_t i, n;
15087 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015088
Benjamin Peterson14339b62009-01-31 16:36:08 +000015089 if (interned == NULL || !PyDict_Check(interned))
15090 return;
15091 keys = PyDict_Keys(interned);
15092 if (keys == NULL || !PyList_Check(keys)) {
15093 PyErr_Clear();
15094 return;
15095 }
Walter Dörwald16807132007-05-25 13:52:07 +000015096
Benjamin Peterson14339b62009-01-31 16:36:08 +000015097 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15098 detector, interned unicode strings are not forcibly deallocated;
15099 rather, we give them their stolen references back, and then clear
15100 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015101
Benjamin Peterson14339b62009-01-31 16:36:08 +000015102 n = PyList_GET_SIZE(keys);
15103 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015104 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015105 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015106 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015107 if (PyUnicode_READY(s) == -1) {
15108 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015109 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015111 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 case SSTATE_NOT_INTERNED:
15113 /* XXX Shouldn't happen */
15114 break;
15115 case SSTATE_INTERNED_IMMORTAL:
15116 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015117 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015118 break;
15119 case SSTATE_INTERNED_MORTAL:
15120 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015121 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015122 break;
15123 default:
15124 Py_FatalError("Inconsistent interned string state.");
15125 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015126 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015127 }
15128 fprintf(stderr, "total size of all interned strings: "
15129 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15130 "mortal/immortal\n", mortal_size, immortal_size);
15131 Py_DECREF(keys);
15132 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015133 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015134}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015135
15136
15137/********************* Unicode Iterator **************************/
15138
15139typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015140 PyObject_HEAD
15141 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015142 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015143} unicodeiterobject;
15144
15145static void
15146unicodeiter_dealloc(unicodeiterobject *it)
15147{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 _PyObject_GC_UNTRACK(it);
15149 Py_XDECREF(it->it_seq);
15150 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015151}
15152
15153static int
15154unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15155{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015156 Py_VISIT(it->it_seq);
15157 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015158}
15159
15160static PyObject *
15161unicodeiter_next(unicodeiterobject *it)
15162{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015163 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015164
Benjamin Peterson14339b62009-01-31 16:36:08 +000015165 assert(it != NULL);
15166 seq = it->it_seq;
15167 if (seq == NULL)
15168 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015169 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015171 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15172 int kind = PyUnicode_KIND(seq);
15173 void *data = PyUnicode_DATA(seq);
15174 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15175 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015176 if (item != NULL)
15177 ++it->it_index;
15178 return item;
15179 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015180
Benjamin Peterson14339b62009-01-31 16:36:08 +000015181 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015182 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015183 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015184}
15185
15186static PyObject *
15187unicodeiter_len(unicodeiterobject *it)
15188{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 Py_ssize_t len = 0;
15190 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015191 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015192 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015193}
15194
15195PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15196
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015197static PyObject *
15198unicodeiter_reduce(unicodeiterobject *it)
15199{
15200 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015201 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015202 it->it_seq, it->it_index);
15203 } else {
15204 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15205 if (u == NULL)
15206 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015207 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015208 }
15209}
15210
15211PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15212
15213static PyObject *
15214unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15215{
15216 Py_ssize_t index = PyLong_AsSsize_t(state);
15217 if (index == -1 && PyErr_Occurred())
15218 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015219 if (it->it_seq != NULL) {
15220 if (index < 0)
15221 index = 0;
15222 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15223 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15224 it->it_index = index;
15225 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015226 Py_RETURN_NONE;
15227}
15228
15229PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15230
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015231static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015232 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015233 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015234 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15235 reduce_doc},
15236 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15237 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015239};
15240
15241PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015242 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15243 "str_iterator", /* tp_name */
15244 sizeof(unicodeiterobject), /* tp_basicsize */
15245 0, /* tp_itemsize */
15246 /* methods */
15247 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15248 0, /* tp_print */
15249 0, /* tp_getattr */
15250 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015251 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015252 0, /* tp_repr */
15253 0, /* tp_as_number */
15254 0, /* tp_as_sequence */
15255 0, /* tp_as_mapping */
15256 0, /* tp_hash */
15257 0, /* tp_call */
15258 0, /* tp_str */
15259 PyObject_GenericGetAttr, /* tp_getattro */
15260 0, /* tp_setattro */
15261 0, /* tp_as_buffer */
15262 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15263 0, /* tp_doc */
15264 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15265 0, /* tp_clear */
15266 0, /* tp_richcompare */
15267 0, /* tp_weaklistoffset */
15268 PyObject_SelfIter, /* tp_iter */
15269 (iternextfunc)unicodeiter_next, /* tp_iternext */
15270 unicodeiter_methods, /* tp_methods */
15271 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015272};
15273
15274static PyObject *
15275unicode_iter(PyObject *seq)
15276{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015278
Benjamin Peterson14339b62009-01-31 16:36:08 +000015279 if (!PyUnicode_Check(seq)) {
15280 PyErr_BadInternalCall();
15281 return NULL;
15282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015283 if (PyUnicode_READY(seq) == -1)
15284 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015285 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15286 if (it == NULL)
15287 return NULL;
15288 it->it_index = 0;
15289 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015290 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 _PyObject_GC_TRACK(it);
15292 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015293}
15294
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015295
15296size_t
15297Py_UNICODE_strlen(const Py_UNICODE *u)
15298{
15299 int res = 0;
15300 while(*u++)
15301 res++;
15302 return res;
15303}
15304
15305Py_UNICODE*
15306Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15307{
15308 Py_UNICODE *u = s1;
15309 while ((*u++ = *s2++));
15310 return s1;
15311}
15312
15313Py_UNICODE*
15314Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15315{
15316 Py_UNICODE *u = s1;
15317 while ((*u++ = *s2++))
15318 if (n-- == 0)
15319 break;
15320 return s1;
15321}
15322
15323Py_UNICODE*
15324Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15325{
15326 Py_UNICODE *u1 = s1;
15327 u1 += Py_UNICODE_strlen(u1);
15328 Py_UNICODE_strcpy(u1, s2);
15329 return s1;
15330}
15331
15332int
15333Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15334{
15335 while (*s1 && *s2 && *s1 == *s2)
15336 s1++, s2++;
15337 if (*s1 && *s2)
15338 return (*s1 < *s2) ? -1 : +1;
15339 if (*s1)
15340 return 1;
15341 if (*s2)
15342 return -1;
15343 return 0;
15344}
15345
15346int
15347Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15348{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015349 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015350 for (; n != 0; n--) {
15351 u1 = *s1;
15352 u2 = *s2;
15353 if (u1 != u2)
15354 return (u1 < u2) ? -1 : +1;
15355 if (u1 == '\0')
15356 return 0;
15357 s1++;
15358 s2++;
15359 }
15360 return 0;
15361}
15362
15363Py_UNICODE*
15364Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15365{
15366 const Py_UNICODE *p;
15367 for (p = s; *p; p++)
15368 if (*p == c)
15369 return (Py_UNICODE*)p;
15370 return NULL;
15371}
15372
15373Py_UNICODE*
15374Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15375{
15376 const Py_UNICODE *p;
15377 p = s + Py_UNICODE_strlen(s);
15378 while (p != s) {
15379 p--;
15380 if (*p == c)
15381 return (Py_UNICODE*)p;
15382 }
15383 return NULL;
15384}
Victor Stinner331ea922010-08-10 16:37:20 +000015385
Victor Stinner71133ff2010-09-01 23:43:53 +000015386Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015387PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015388{
Victor Stinner577db2c2011-10-11 22:12:48 +020015389 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015390 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015392 if (!PyUnicode_Check(unicode)) {
15393 PyErr_BadArgument();
15394 return NULL;
15395 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015396 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015397 if (u == NULL)
15398 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015399 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015400 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015401 PyErr_NoMemory();
15402 return NULL;
15403 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015404 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015405 size *= sizeof(Py_UNICODE);
15406 copy = PyMem_Malloc(size);
15407 if (copy == NULL) {
15408 PyErr_NoMemory();
15409 return NULL;
15410 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015411 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015412 return copy;
15413}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015414
Georg Brandl66c221e2010-10-14 07:04:07 +000015415/* A _string module, to export formatter_parser and formatter_field_name_split
15416 to the string.Formatter class implemented in Python. */
15417
15418static PyMethodDef _string_methods[] = {
15419 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15420 METH_O, PyDoc_STR("split the argument as a field name")},
15421 {"formatter_parser", (PyCFunction) formatter_parser,
15422 METH_O, PyDoc_STR("parse the argument as a format string")},
15423 {NULL, NULL}
15424};
15425
15426static struct PyModuleDef _string_module = {
15427 PyModuleDef_HEAD_INIT,
15428 "_string",
15429 PyDoc_STR("string helper module"),
15430 0,
15431 _string_methods,
15432 NULL,
15433 NULL,
15434 NULL,
15435 NULL
15436};
15437
15438PyMODINIT_FUNC
15439PyInit__string(void)
15440{
15441 return PyModule_Create(&_string_module);
15442}
15443
15444
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015445#ifdef __cplusplus
15446}
15447#endif