blob: ab80e24373058f4e4b339a1f474405d96590beee [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070045#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000046
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000047#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000048#include <windows.h>
49#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000050
Larry Hastings61272b72014-01-07 12:41:53 -080051/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080052class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080053[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080054/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080055
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000056/* --- Globals ------------------------------------------------------------
57
Serhiy Storchaka05997252013-01-26 12:14:02 +020058NOTE: In the interpreter's initialization phase, some globals are currently
59 initialized dynamically as needed. In the process Unicode objects may
60 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200131 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200138 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200139 (!PyUnicode_IS_READY(op) || \
140 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
141
Victor Stinner910337b2011-10-03 03:20:16 +0200142/* Generic helper macro to convert characters of different types.
143 from_type and to_type have to be valid type names, begin and end
144 are pointers to the source characters which should be of type
145 "from_type *". to is a pointer of type "to_type *" and points to the
146 buffer where the result characters are written to. */
147#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
148 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100149 to_type *_to = (to_type *)(to); \
150 const from_type *_iter = (from_type *)(begin); \
151 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 Py_ssize_t n = (_end) - (_iter); \
153 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200154 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200155 while (_iter < (_unrolled_end)) { \
156 _to[0] = (to_type) _iter[0]; \
157 _to[1] = (to_type) _iter[1]; \
158 _to[2] = (to_type) _iter[2]; \
159 _to[3] = (to_type) _iter[3]; \
160 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200161 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200162 while (_iter < (_end)) \
163 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200165
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200166#ifdef MS_WINDOWS
167 /* On Windows, overallocate by 50% is the best factor */
168# define OVERALLOCATE_FACTOR 2
169#else
170 /* On Linux, overallocate by 25% is the best factor */
171# define OVERALLOCATE_FACTOR 4
172#endif
173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 do { \
189 if (unicode_empty != NULL) \
190 Py_INCREF(unicode_empty); \
191 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192 unicode_empty = PyUnicode_New(0, 0); \
193 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200195 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
196 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200#define _Py_RETURN_UNICODE_EMPTY() \
201 do { \
202 _Py_INCREF_UNICODE_EMPTY(); \
203 return unicode_empty; \
204 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200206/* Forward declaration */
207Py_LOCAL_INLINE(int)
208_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
209
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200210/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200212
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213/* Single character Unicode strings in the Latin-1 range are being
214 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Christian Heimes190d79e2008-01-30 11:58:22 +0000217/* Fast detection of the most frequent whitespace characters */
218const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000220/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000222/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x000C: * FORM FEED */
224/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 0, 1, 1, 1, 1, 1, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000227/* case 0x001C: * FILE SEPARATOR */
228/* case 0x001D: * GROUP SEPARATOR */
229/* case 0x001E: * RECORD SEPARATOR */
230/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000232/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000233 1, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000237
Benjamin Peterson14339b62009-01-31 16:36:08 +0000238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000246};
247
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200248/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200250static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100251static int unicode_modifiable(PyObject *unicode);
252
Victor Stinnerfe226c02011-10-03 03:52:20 +0200253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100255_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200256static PyObject *
257_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
258static PyObject *
259_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
260
261static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000263 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100264 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000265 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
266
Alexander Belopolsky40018472011-02-26 01:02:56 +0000267static void
268raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300269 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100270 PyObject *unicode,
271 Py_ssize_t startpos, Py_ssize_t endpos,
272 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200275static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278/* 0x000B, * LINE TABULATION */
279/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000281 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000283/* 0x001C, * FILE SEPARATOR */
284/* 0x001D, * GROUP SEPARATOR */
285/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 1, 1, 1, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000291
Benjamin Peterson14339b62009-01-31 16:36:08 +0000292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000300};
301
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300302#include "clinic/unicodeobject.c.h"
303
Victor Stinner50149202015-09-22 00:26:54 +0200304typedef enum {
305 _Py_ERROR_UNKNOWN=0,
306 _Py_ERROR_STRICT,
307 _Py_ERROR_SURROGATEESCAPE,
308 _Py_ERROR_REPLACE,
309 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200310 _Py_ERROR_BACKSLASHREPLACE,
311 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200312 _Py_ERROR_XMLCHARREFREPLACE,
313 _Py_ERROR_OTHER
314} _Py_error_handler;
315
316static _Py_error_handler
317get_error_handler(const char *errors)
318{
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0)
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
321 if (strcmp(errors, "surrogateescape") == 0)
322 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner50149202015-09-22 00:26:54 +0200323 if (strcmp(errors, "replace") == 0)
324 return _Py_ERROR_REPLACE;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200325 if (strcmp(errors, "ignore") == 0)
326 return _Py_ERROR_IGNORE;
327 if (strcmp(errors, "backslashreplace") == 0)
328 return _Py_ERROR_BACKSLASHREPLACE;
329 if (strcmp(errors, "surrogatepass") == 0)
330 return _Py_ERROR_SURROGATEPASS;
Victor Stinner50149202015-09-22 00:26:54 +0200331 if (strcmp(errors, "xmlcharrefreplace") == 0)
332 return _Py_ERROR_XMLCHARREFREPLACE;
333 return _Py_ERROR_OTHER;
334}
335
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300336/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
337 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000338Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000339PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000340{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000341#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000342 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000343#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000344 /* This is actually an illegal character, so it should
345 not be passed to unichr. */
346 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347#endif
348}
349
Victor Stinner910337b2011-10-03 03:20:16 +0200350#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200351int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100352_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200353{
354 PyASCIIObject *ascii;
355 unsigned int kind;
356
357 assert(PyUnicode_Check(op));
358
359 ascii = (PyASCIIObject *)op;
360 kind = ascii->state.kind;
361
Victor Stinnera3b334d2011-10-03 13:53:37 +0200362 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200363 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200364 assert(ascii->state.ready == 1);
365 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200366 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200367 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200368 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200369
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 if (ascii->state.compact == 1) {
371 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200372 assert(kind == PyUnicode_1BYTE_KIND
373 || kind == PyUnicode_2BYTE_KIND
374 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200375 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200376 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100378 }
379 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200380 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
381
382 data = unicode->data.any;
383 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100384 assert(ascii->length == 0);
385 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200386 assert(ascii->state.compact == 0);
387 assert(ascii->state.ascii == 0);
388 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100389 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 assert(ascii->wstr != NULL);
391 assert(data == NULL);
392 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 }
394 else {
395 assert(kind == PyUnicode_1BYTE_KIND
396 || kind == PyUnicode_2BYTE_KIND
397 || kind == PyUnicode_4BYTE_KIND);
398 assert(ascii->state.compact == 0);
399 assert(ascii->state.ready == 1);
400 assert(data != NULL);
401 if (ascii->state.ascii) {
402 assert (compact->utf8 == data);
403 assert (compact->utf8_length == ascii->length);
404 }
405 else
406 assert (compact->utf8 != data);
407 }
408 }
409 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200410 if (
411#if SIZEOF_WCHAR_T == 2
412 kind == PyUnicode_2BYTE_KIND
413#else
414 kind == PyUnicode_4BYTE_KIND
415#endif
416 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 {
418 assert(ascii->wstr == data);
419 assert(compact->wstr_length == ascii->length);
420 } else
421 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200422 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200423
424 if (compact->utf8 == NULL)
425 assert(compact->utf8_length == 0);
426 if (ascii->wstr == NULL)
427 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200428 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200429 /* check that the best kind is used */
430 if (check_content && kind != PyUnicode_WCHAR_KIND)
431 {
432 Py_ssize_t i;
433 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200434 void *data;
435 Py_UCS4 ch;
436
437 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200438 for (i=0; i < ascii->length; i++)
439 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200440 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200441 if (ch > maxchar)
442 maxchar = ch;
443 }
444 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100445 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200446 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100447 assert(maxchar <= 255);
448 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200449 else
450 assert(maxchar < 128);
451 }
Victor Stinner77faf692011-11-20 18:56:05 +0100452 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 0xFFFF);
455 }
456 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200457 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100458 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100459 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200460 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200461 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400462 return 1;
463}
Victor Stinner910337b2011-10-03 03:20:16 +0200464#endif
465
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466static PyObject*
467unicode_result_wchar(PyObject *unicode)
468{
469#ifndef Py_DEBUG
470 Py_ssize_t len;
471
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100472 len = _PyUnicode_WSTR_LENGTH(unicode);
473 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100474 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200475 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 }
477
478 if (len == 1) {
479 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100480 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
482 Py_DECREF(unicode);
483 return latin1_char;
484 }
485 }
486
487 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200488 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100489 return NULL;
490 }
491#else
Victor Stinneraa771272012-10-04 02:32:58 +0200492 assert(Py_REFCNT(unicode) == 1);
493
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100494 /* don't make the result ready in debug mode to ensure that the caller
495 makes the string ready before using it */
496 assert(_PyUnicode_CheckConsistency(unicode, 1));
497#endif
498 return unicode;
499}
500
501static PyObject*
502unicode_result_ready(PyObject *unicode)
503{
504 Py_ssize_t length;
505
506 length = PyUnicode_GET_LENGTH(unicode);
507 if (length == 0) {
508 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100509 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200510 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100511 }
512 return unicode_empty;
513 }
514
515 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200516 void *data = PyUnicode_DATA(unicode);
517 int kind = PyUnicode_KIND(unicode);
518 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100519 if (ch < 256) {
520 PyObject *latin1_char = unicode_latin1[ch];
521 if (latin1_char != NULL) {
522 if (unicode != latin1_char) {
523 Py_INCREF(latin1_char);
524 Py_DECREF(unicode);
525 }
526 return latin1_char;
527 }
528 else {
529 assert(_PyUnicode_CheckConsistency(unicode, 1));
530 Py_INCREF(unicode);
531 unicode_latin1[ch] = unicode;
532 return unicode;
533 }
534 }
535 }
536
537 assert(_PyUnicode_CheckConsistency(unicode, 1));
538 return unicode;
539}
540
541static PyObject*
542unicode_result(PyObject *unicode)
543{
544 assert(_PyUnicode_CHECK(unicode));
545 if (PyUnicode_IS_READY(unicode))
546 return unicode_result_ready(unicode);
547 else
548 return unicode_result_wchar(unicode);
549}
550
Victor Stinnerc4b49542011-12-11 22:44:26 +0100551static PyObject*
552unicode_result_unchanged(PyObject *unicode)
553{
554 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500555 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100556 return NULL;
557 Py_INCREF(unicode);
558 return unicode;
559 }
560 else
561 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100562 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563}
564
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200565/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
566 ASCII, Latin1, UTF-8, etc. */
567static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200568backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200569 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
570{
Victor Stinnerad771582015-10-09 12:38:53 +0200571 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572 Py_UCS4 ch;
573 enum PyUnicode_Kind kind;
574 void *data;
575
576 assert(PyUnicode_IS_READY(unicode));
577 kind = PyUnicode_KIND(unicode);
578 data = PyUnicode_DATA(unicode);
579
580 size = 0;
581 /* determine replacement size */
582 for (i = collstart; i < collend; ++i) {
583 Py_ssize_t incr;
584
585 ch = PyUnicode_READ(kind, data, i);
586 if (ch < 0x100)
587 incr = 2+2;
588 else if (ch < 0x10000)
589 incr = 2+4;
590 else {
591 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200592 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 }
594 if (size > PY_SSIZE_T_MAX - incr) {
595 PyErr_SetString(PyExc_OverflowError,
596 "encoded result is too long for a Python string");
597 return NULL;
598 }
599 size += incr;
600 }
601
Victor Stinnerad771582015-10-09 12:38:53 +0200602 str = _PyBytesWriter_Prepare(writer, str, size);
603 if (str == NULL)
604 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200605
606 /* generate replacement */
607 for (i = collstart; i < collend; ++i) {
608 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200609 *str++ = '\\';
610 if (ch >= 0x00010000) {
611 *str++ = 'U';
612 *str++ = Py_hexdigits[(ch>>28)&0xf];
613 *str++ = Py_hexdigits[(ch>>24)&0xf];
614 *str++ = Py_hexdigits[(ch>>20)&0xf];
615 *str++ = Py_hexdigits[(ch>>16)&0xf];
616 *str++ = Py_hexdigits[(ch>>12)&0xf];
617 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200618 }
Victor Stinner797485e2015-10-09 03:17:30 +0200619 else if (ch >= 0x100) {
620 *str++ = 'u';
621 *str++ = Py_hexdigits[(ch>>12)&0xf];
622 *str++ = Py_hexdigits[(ch>>8)&0xf];
623 }
624 else
625 *str++ = 'x';
626 *str++ = Py_hexdigits[(ch>>4)&0xf];
627 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200628 }
629 return str;
630}
631
632/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
633 ASCII, Latin1, UTF-8, etc. */
634static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200635xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200636 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
637{
Victor Stinnerad771582015-10-09 12:38:53 +0200638 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200639 Py_UCS4 ch;
640 enum PyUnicode_Kind kind;
641 void *data;
642
643 assert(PyUnicode_IS_READY(unicode));
644 kind = PyUnicode_KIND(unicode);
645 data = PyUnicode_DATA(unicode);
646
647 size = 0;
648 /* determine replacement size */
649 for (i = collstart; i < collend; ++i) {
650 Py_ssize_t incr;
651
652 ch = PyUnicode_READ(kind, data, i);
653 if (ch < 10)
654 incr = 2+1+1;
655 else if (ch < 100)
656 incr = 2+2+1;
657 else if (ch < 1000)
658 incr = 2+3+1;
659 else if (ch < 10000)
660 incr = 2+4+1;
661 else if (ch < 100000)
662 incr = 2+5+1;
663 else if (ch < 1000000)
664 incr = 2+6+1;
665 else {
666 assert(ch <= MAX_UNICODE);
667 incr = 2+7+1;
668 }
669 if (size > PY_SSIZE_T_MAX - incr) {
670 PyErr_SetString(PyExc_OverflowError,
671 "encoded result is too long for a Python string");
672 return NULL;
673 }
674 size += incr;
675 }
676
Victor Stinnerad771582015-10-09 12:38:53 +0200677 str = _PyBytesWriter_Prepare(writer, str, size);
678 if (str == NULL)
679 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200680
681 /* generate replacement */
682 for (i = collstart; i < collend; ++i) {
683 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
684 }
685 return str;
686}
687
Thomas Wouters477c8d52006-05-27 19:21:47 +0000688/* --- Bloom Filters ----------------------------------------------------- */
689
690/* stuff to implement simple "bloom filters" for Unicode characters.
691 to keep things simple, we use a single bitmask, using the least 5
692 bits from each unicode characters as the bit index. */
693
694/* the linebreak mask is set up by Unicode_Init below */
695
Antoine Pitrouf068f942010-01-13 14:19:12 +0000696#if LONG_BIT >= 128
697#define BLOOM_WIDTH 128
698#elif LONG_BIT >= 64
699#define BLOOM_WIDTH 64
700#elif LONG_BIT >= 32
701#define BLOOM_WIDTH 32
702#else
703#error "LONG_BIT is smaller than 32"
704#endif
705
Thomas Wouters477c8d52006-05-27 19:21:47 +0000706#define BLOOM_MASK unsigned long
707
Serhiy Storchaka05997252013-01-26 12:14:02 +0200708static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000709
Antoine Pitrouf068f942010-01-13 14:19:12 +0000710#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711
Benjamin Peterson29060642009-01-31 22:14:21 +0000712#define BLOOM_LINEBREAK(ch) \
713 ((ch) < 128U ? ascii_linebreak[(ch)] : \
714 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000715
Alexander Belopolsky40018472011-02-26 01:02:56 +0000716Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200717make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718{
Victor Stinnera85af502013-04-09 21:53:54 +0200719#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
720 do { \
721 TYPE *data = (TYPE *)PTR; \
722 TYPE *end = data + LEN; \
723 Py_UCS4 ch; \
724 for (; data != end; data++) { \
725 ch = *data; \
726 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
727 } \
728 break; \
729 } while (0)
730
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731 /* calculate simple bloom-style bitmask for a given unicode string */
732
Antoine Pitrouf068f942010-01-13 14:19:12 +0000733 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000734
735 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200736 switch (kind) {
737 case PyUnicode_1BYTE_KIND:
738 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
739 break;
740 case PyUnicode_2BYTE_KIND:
741 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
742 break;
743 case PyUnicode_4BYTE_KIND:
744 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
745 break;
746 default:
747 assert(0);
748 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000749 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200750
751#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000752}
753
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200754/* Compilation of templated routines */
755
756#include "stringlib/asciilib.h"
757#include "stringlib/fastsearch.h"
758#include "stringlib/partition.h"
759#include "stringlib/split.h"
760#include "stringlib/count.h"
761#include "stringlib/find.h"
762#include "stringlib/find_max_char.h"
763#include "stringlib/localeutil.h"
764#include "stringlib/undef.h"
765
766#include "stringlib/ucs1lib.h"
767#include "stringlib/fastsearch.h"
768#include "stringlib/partition.h"
769#include "stringlib/split.h"
770#include "stringlib/count.h"
771#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300772#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773#include "stringlib/find_max_char.h"
774#include "stringlib/localeutil.h"
775#include "stringlib/undef.h"
776
777#include "stringlib/ucs2lib.h"
778#include "stringlib/fastsearch.h"
779#include "stringlib/partition.h"
780#include "stringlib/split.h"
781#include "stringlib/count.h"
782#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300783#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200784#include "stringlib/find_max_char.h"
785#include "stringlib/localeutil.h"
786#include "stringlib/undef.h"
787
788#include "stringlib/ucs4lib.h"
789#include "stringlib/fastsearch.h"
790#include "stringlib/partition.h"
791#include "stringlib/split.h"
792#include "stringlib/count.h"
793#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300794#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200795#include "stringlib/find_max_char.h"
796#include "stringlib/localeutil.h"
797#include "stringlib/undef.h"
798
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200799#include "stringlib/unicodedefs.h"
800#include "stringlib/fastsearch.h"
801#include "stringlib/count.h"
802#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100803#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200804
Guido van Rossumd57fd912000-03-10 22:53:23 +0000805/* --- Unicode Object ----------------------------------------------------- */
806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200807static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200808fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200809
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200810Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200811 Py_ssize_t size, Py_UCS4 ch,
812 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200813{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200814 switch (kind) {
815 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200816 if ((Py_UCS1) ch != ch)
817 return -1;
818 if (direction > 0)
819 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
820 else
821 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200822 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200823 if ((Py_UCS2) ch != ch)
824 return -1;
825 if (direction > 0)
826 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
827 else
828 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200829 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200830 if (direction > 0)
831 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
832 else
833 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 default:
835 assert(0);
836 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200838}
839
Victor Stinnerafffce42012-10-03 23:03:17 +0200840#ifdef Py_DEBUG
841/* Fill the data of an Unicode string with invalid characters to detect bugs
842 earlier.
843
844 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
845 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
846 invalid character in Unicode 6.0. */
847static void
848unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
849{
850 int kind = PyUnicode_KIND(unicode);
851 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
852 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
853 if (length <= old_length)
854 return;
855 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
856}
857#endif
858
Victor Stinnerfe226c02011-10-03 03:52:20 +0200859static PyObject*
860resize_compact(PyObject *unicode, Py_ssize_t length)
861{
862 Py_ssize_t char_size;
863 Py_ssize_t struct_size;
864 Py_ssize_t new_size;
865 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100866 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200867#ifdef Py_DEBUG
868 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
869#endif
870
Victor Stinner79891572012-05-03 13:43:07 +0200871 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200872 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100873 assert(PyUnicode_IS_COMPACT(unicode));
874
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200875 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100876 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200877 struct_size = sizeof(PyASCIIObject);
878 else
879 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200880 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200881
Victor Stinnerfe226c02011-10-03 03:52:20 +0200882 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
883 PyErr_NoMemory();
884 return NULL;
885 }
886 new_size = (struct_size + (length + 1) * char_size);
887
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200888 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
889 PyObject_DEL(_PyUnicode_UTF8(unicode));
890 _PyUnicode_UTF8(unicode) = NULL;
891 _PyUnicode_UTF8_LENGTH(unicode) = 0;
892 }
Victor Stinner84def372011-12-11 20:04:56 +0100893 _Py_DEC_REFTOTAL;
894 _Py_ForgetReference(unicode);
895
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300896 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100897 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100898 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200899 PyErr_NoMemory();
900 return NULL;
901 }
Victor Stinner84def372011-12-11 20:04:56 +0100902 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200903 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100904
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200906 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200907 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100908 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200909 _PyUnicode_WSTR_LENGTH(unicode) = length;
910 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100911 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
912 PyObject_DEL(_PyUnicode_WSTR(unicode));
913 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100914 if (!PyUnicode_IS_ASCII(unicode))
915 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100916 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200917#ifdef Py_DEBUG
918 unicode_fill_invalid(unicode, old_length);
919#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200920 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
921 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200922 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200923 return unicode;
924}
925
Alexander Belopolsky40018472011-02-26 01:02:56 +0000926static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200927resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000928{
Victor Stinner95663112011-10-04 01:03:50 +0200929 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100930 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000933
Victor Stinnerfe226c02011-10-03 03:52:20 +0200934 if (PyUnicode_IS_READY(unicode)) {
935 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200936 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200937 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200938#ifdef Py_DEBUG
939 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
940#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200941
942 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200943 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200944 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
945 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200946
947 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
948 PyErr_NoMemory();
949 return -1;
950 }
951 new_size = (length + 1) * char_size;
952
Victor Stinner7a9105a2011-12-12 00:13:42 +0100953 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
954 {
955 PyObject_DEL(_PyUnicode_UTF8(unicode));
956 _PyUnicode_UTF8(unicode) = NULL;
957 _PyUnicode_UTF8_LENGTH(unicode) = 0;
958 }
959
Victor Stinnerfe226c02011-10-03 03:52:20 +0200960 data = (PyObject *)PyObject_REALLOC(data, new_size);
961 if (data == NULL) {
962 PyErr_NoMemory();
963 return -1;
964 }
965 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200966 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200968 _PyUnicode_WSTR_LENGTH(unicode) = length;
969 }
970 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200971 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200972 _PyUnicode_UTF8_LENGTH(unicode) = length;
973 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974 _PyUnicode_LENGTH(unicode) = length;
975 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200976#ifdef Py_DEBUG
977 unicode_fill_invalid(unicode, old_length);
978#endif
Victor Stinner95663112011-10-04 01:03:50 +0200979 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200980 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200981 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200982 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200983 }
Victor Stinner95663112011-10-04 01:03:50 +0200984 assert(_PyUnicode_WSTR(unicode) != NULL);
985
986 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700987 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200988 PyErr_NoMemory();
989 return -1;
990 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100991 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200992 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100993 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200994 if (!wstr) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_WSTR(unicode) = wstr;
999 _PyUnicode_WSTR(unicode)[length] = 0;
1000 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001001 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001002 return 0;
1003}
1004
Victor Stinnerfe226c02011-10-03 03:52:20 +02001005static PyObject*
1006resize_copy(PyObject *unicode, Py_ssize_t length)
1007{
1008 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001009 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001010 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011
Benjamin Petersonbac79492012-01-14 13:34:47 -05001012 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001013 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014
1015 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1016 if (copy == NULL)
1017 return NULL;
1018
1019 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001020 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001021 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001022 }
1023 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001024 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001025
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001026 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001027 if (w == NULL)
1028 return NULL;
1029 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1030 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001031 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1032 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001033 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001034 }
1035}
1036
Guido van Rossumd57fd912000-03-10 22:53:23 +00001037/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001038 Ux0000 terminated; some code (e.g. new_identifier)
1039 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001040
1041 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001042 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001043
1044*/
1045
Alexander Belopolsky40018472011-02-26 01:02:56 +00001046static PyUnicodeObject *
1047_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001048{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001049 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001051
Thomas Wouters477c8d52006-05-27 19:21:47 +00001052 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001053 if (length == 0 && unicode_empty != NULL) {
1054 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001055 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056 }
1057
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001058 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001059 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001060 return (PyUnicodeObject *)PyErr_NoMemory();
1061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062 if (length < 0) {
1063 PyErr_SetString(PyExc_SystemError,
1064 "Negative size passed to _PyUnicode_New");
1065 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001066 }
1067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1069 if (unicode == NULL)
1070 return NULL;
1071 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001072
1073 _PyUnicode_WSTR_LENGTH(unicode) = length;
1074 _PyUnicode_HASH(unicode) = -1;
1075 _PyUnicode_STATE(unicode).interned = 0;
1076 _PyUnicode_STATE(unicode).kind = 0;
1077 _PyUnicode_STATE(unicode).compact = 0;
1078 _PyUnicode_STATE(unicode).ready = 0;
1079 _PyUnicode_STATE(unicode).ascii = 0;
1080 _PyUnicode_DATA_ANY(unicode) = NULL;
1081 _PyUnicode_LENGTH(unicode) = 0;
1082 _PyUnicode_UTF8(unicode) = NULL;
1083 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1086 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001087 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001088 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001089 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001090 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091
Jeremy Hyltond8082792003-09-16 19:41:39 +00001092 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001093 * the caller fails before initializing str -- unicode_resize()
1094 * reads str[0], and the Keep-Alive optimization can keep memory
1095 * allocated for str alive across a call to unicode_dealloc(unicode).
1096 * We don't want unicode_resize to read uninitialized memory in
1097 * that case.
1098 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001099 _PyUnicode_WSTR(unicode)[0] = 0;
1100 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001101
Victor Stinner7931d9a2011-11-04 00:22:48 +01001102 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001103 return unicode;
1104}
1105
Victor Stinnerf42dc442011-10-02 23:33:16 +02001106static const char*
1107unicode_kind_name(PyObject *unicode)
1108{
Victor Stinner42dfd712011-10-03 14:41:45 +02001109 /* don't check consistency: unicode_kind_name() is called from
1110 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001111 if (!PyUnicode_IS_COMPACT(unicode))
1112 {
1113 if (!PyUnicode_IS_READY(unicode))
1114 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001115 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001116 {
1117 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001118 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 return "legacy ascii";
1120 else
1121 return "legacy latin1";
1122 case PyUnicode_2BYTE_KIND:
1123 return "legacy UCS2";
1124 case PyUnicode_4BYTE_KIND:
1125 return "legacy UCS4";
1126 default:
1127 return "<legacy invalid kind>";
1128 }
1129 }
1130 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001131 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001132 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001133 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001134 return "ascii";
1135 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001136 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001137 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001140 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001141 default:
1142 return "<invalid compact kind>";
1143 }
1144}
1145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147/* Functions wrapping macros for use in debugger */
1148char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001149 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150}
1151
1152void *_PyUnicode_compact_data(void *unicode) {
1153 return _PyUnicode_COMPACT_DATA(unicode);
1154}
1155void *_PyUnicode_data(void *unicode){
1156 printf("obj %p\n", unicode);
1157 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1158 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1159 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1160 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1161 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1162 return PyUnicode_DATA(unicode);
1163}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001164
1165void
1166_PyUnicode_Dump(PyObject *op)
1167{
1168 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001169 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1170 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1171 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001172
Victor Stinnera849a4b2011-10-03 12:12:11 +02001173 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001174 {
1175 if (ascii->state.ascii)
1176 data = (ascii + 1);
1177 else
1178 data = (compact + 1);
1179 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001180 else
1181 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001182 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1183 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001184
Victor Stinnera849a4b2011-10-03 12:12:11 +02001185 if (ascii->wstr == data)
1186 printf("shared ");
1187 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001188
Victor Stinnera3b334d2011-10-03 13:53:37 +02001189 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001190 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001191 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1192 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001193 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1194 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001195 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001196 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001197}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198#endif
1199
1200PyObject *
1201PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1202{
1203 PyObject *obj;
1204 PyCompactUnicodeObject *unicode;
1205 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001206 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001207 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208 Py_ssize_t char_size;
1209 Py_ssize_t struct_size;
1210
1211 /* Optimization for empty strings */
1212 if (size == 0 && unicode_empty != NULL) {
1213 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001214 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001215 }
1216
Victor Stinner9e9d6892011-10-04 01:02:02 +02001217 is_ascii = 0;
1218 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 struct_size = sizeof(PyCompactUnicodeObject);
1220 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001221 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001222 char_size = 1;
1223 is_ascii = 1;
1224 struct_size = sizeof(PyASCIIObject);
1225 }
1226 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001227 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 char_size = 1;
1229 }
1230 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001231 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001232 char_size = 2;
1233 if (sizeof(wchar_t) == 2)
1234 is_sharing = 1;
1235 }
1236 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001237 if (maxchar > MAX_UNICODE) {
1238 PyErr_SetString(PyExc_SystemError,
1239 "invalid maximum character passed to PyUnicode_New");
1240 return NULL;
1241 }
Victor Stinner8f825062012-04-27 13:55:39 +02001242 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001243 char_size = 4;
1244 if (sizeof(wchar_t) == 4)
1245 is_sharing = 1;
1246 }
1247
1248 /* Ensure we won't overflow the size. */
1249 if (size < 0) {
1250 PyErr_SetString(PyExc_SystemError,
1251 "Negative size passed to PyUnicode_New");
1252 return NULL;
1253 }
1254 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1255 return PyErr_NoMemory();
1256
1257 /* Duplicated allocation code from _PyObject_New() instead of a call to
1258 * PyObject_New() so we are able to allocate space for the object and
1259 * it's data buffer.
1260 */
1261 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1262 if (obj == NULL)
1263 return PyErr_NoMemory();
1264 obj = PyObject_INIT(obj, &PyUnicode_Type);
1265 if (obj == NULL)
1266 return NULL;
1267
1268 unicode = (PyCompactUnicodeObject *)obj;
1269 if (is_ascii)
1270 data = ((PyASCIIObject*)obj) + 1;
1271 else
1272 data = unicode + 1;
1273 _PyUnicode_LENGTH(unicode) = size;
1274 _PyUnicode_HASH(unicode) = -1;
1275 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001276 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001277 _PyUnicode_STATE(unicode).compact = 1;
1278 _PyUnicode_STATE(unicode).ready = 1;
1279 _PyUnicode_STATE(unicode).ascii = is_ascii;
1280 if (is_ascii) {
1281 ((char*)data)[size] = 0;
1282 _PyUnicode_WSTR(unicode) = NULL;
1283 }
Victor Stinner8f825062012-04-27 13:55:39 +02001284 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285 ((char*)data)[size] = 0;
1286 _PyUnicode_WSTR(unicode) = NULL;
1287 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001288 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001289 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001291 else {
1292 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001293 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001294 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001295 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001296 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 ((Py_UCS4*)data)[size] = 0;
1298 if (is_sharing) {
1299 _PyUnicode_WSTR_LENGTH(unicode) = size;
1300 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1301 }
1302 else {
1303 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1304 _PyUnicode_WSTR(unicode) = NULL;
1305 }
1306 }
Victor Stinner8f825062012-04-27 13:55:39 +02001307#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001308 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001309#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001310 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 return obj;
1312}
1313
1314#if SIZEOF_WCHAR_T == 2
1315/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1316 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001317 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001318
1319 This function assumes that unicode can hold one more code point than wstr
1320 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001321static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001323 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324{
1325 const wchar_t *iter;
1326 Py_UCS4 *ucs4_out;
1327
Victor Stinner910337b2011-10-03 03:20:16 +02001328 assert(unicode != NULL);
1329 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1331 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1332
1333 for (iter = begin; iter < end; ) {
1334 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1335 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001336 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1337 && (iter+1) < end
1338 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001339 {
Victor Stinner551ac952011-11-29 22:58:13 +01001340 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341 iter += 2;
1342 }
1343 else {
1344 *ucs4_out++ = *iter;
1345 iter++;
1346 }
1347 }
1348 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1349 _PyUnicode_GET_LENGTH(unicode)));
1350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351}
1352#endif
1353
Victor Stinnercd9950f2011-10-02 00:34:53 +02001354static int
Victor Stinner488fa492011-12-12 00:01:39 +01001355unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001356{
Victor Stinner488fa492011-12-12 00:01:39 +01001357 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001358 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001359 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001360 return -1;
1361 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001362 return 0;
1363}
1364
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001365static int
1366_copy_characters(PyObject *to, Py_ssize_t to_start,
1367 PyObject *from, Py_ssize_t from_start,
1368 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001370 unsigned int from_kind, to_kind;
1371 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372
Victor Stinneree4544c2012-05-09 22:24:08 +02001373 assert(0 <= how_many);
1374 assert(0 <= from_start);
1375 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001376 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001378 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001379
Victor Stinnerd3f08822012-05-29 12:57:52 +02001380 assert(PyUnicode_Check(to));
1381 assert(PyUnicode_IS_READY(to));
1382 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1383
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001384 if (how_many == 0)
1385 return 0;
1386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001388 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001390 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinnerf1852262012-06-16 16:38:26 +02001392#ifdef Py_DEBUG
1393 if (!check_maxchar
1394 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1395 {
1396 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1397 Py_UCS4 ch;
1398 Py_ssize_t i;
1399 for (i=0; i < how_many; i++) {
1400 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1401 assert(ch <= to_maxchar);
1402 }
1403 }
1404#endif
1405
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001406 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001407 if (check_maxchar
1408 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1409 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001410 /* Writing Latin-1 characters into an ASCII string requires to
1411 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001412 Py_UCS4 max_char;
1413 max_char = ucs1lib_find_max_char(from_data,
1414 (Py_UCS1*)from_data + how_many);
1415 if (max_char >= 128)
1416 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001417 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001418 Py_MEMCPY((char*)to_data + to_kind * to_start,
1419 (char*)from_data + from_kind * from_start,
1420 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 else if (from_kind == PyUnicode_1BYTE_KIND
1423 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001424 {
1425 _PyUnicode_CONVERT_BYTES(
1426 Py_UCS1, Py_UCS2,
1427 PyUnicode_1BYTE_DATA(from) + from_start,
1428 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1429 PyUnicode_2BYTE_DATA(to) + to_start
1430 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001431 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001432 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001433 && to_kind == PyUnicode_4BYTE_KIND)
1434 {
1435 _PyUnicode_CONVERT_BYTES(
1436 Py_UCS1, Py_UCS4,
1437 PyUnicode_1BYTE_DATA(from) + from_start,
1438 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1439 PyUnicode_4BYTE_DATA(to) + to_start
1440 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001441 }
1442 else if (from_kind == PyUnicode_2BYTE_KIND
1443 && to_kind == PyUnicode_4BYTE_KIND)
1444 {
1445 _PyUnicode_CONVERT_BYTES(
1446 Py_UCS2, Py_UCS4,
1447 PyUnicode_2BYTE_DATA(from) + from_start,
1448 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1449 PyUnicode_4BYTE_DATA(to) + to_start
1450 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001451 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001452 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001453 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1454
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001455 if (!check_maxchar) {
1456 if (from_kind == PyUnicode_2BYTE_KIND
1457 && to_kind == PyUnicode_1BYTE_KIND)
1458 {
1459 _PyUnicode_CONVERT_BYTES(
1460 Py_UCS2, Py_UCS1,
1461 PyUnicode_2BYTE_DATA(from) + from_start,
1462 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1463 PyUnicode_1BYTE_DATA(to) + to_start
1464 );
1465 }
1466 else if (from_kind == PyUnicode_4BYTE_KIND
1467 && to_kind == PyUnicode_1BYTE_KIND)
1468 {
1469 _PyUnicode_CONVERT_BYTES(
1470 Py_UCS4, Py_UCS1,
1471 PyUnicode_4BYTE_DATA(from) + from_start,
1472 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1473 PyUnicode_1BYTE_DATA(to) + to_start
1474 );
1475 }
1476 else if (from_kind == PyUnicode_4BYTE_KIND
1477 && to_kind == PyUnicode_2BYTE_KIND)
1478 {
1479 _PyUnicode_CONVERT_BYTES(
1480 Py_UCS4, Py_UCS2,
1481 PyUnicode_4BYTE_DATA(from) + from_start,
1482 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1483 PyUnicode_2BYTE_DATA(to) + to_start
1484 );
1485 }
1486 else {
1487 assert(0);
1488 return -1;
1489 }
1490 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001491 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001492 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001493 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001494 Py_ssize_t i;
1495
Victor Stinnera0702ab2011-09-29 14:14:38 +02001496 for (i=0; i < how_many; i++) {
1497 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001498 if (ch > to_maxchar)
1499 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001500 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1501 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001502 }
1503 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001504 return 0;
1505}
1506
Victor Stinnerd3f08822012-05-29 12:57:52 +02001507void
1508_PyUnicode_FastCopyCharacters(
1509 PyObject *to, Py_ssize_t to_start,
1510 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001511{
1512 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1513}
1514
1515Py_ssize_t
1516PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1517 PyObject *from, Py_ssize_t from_start,
1518 Py_ssize_t how_many)
1519{
1520 int err;
1521
1522 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1523 PyErr_BadInternalCall();
1524 return -1;
1525 }
1526
Benjamin Petersonbac79492012-01-14 13:34:47 -05001527 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001528 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001529 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530 return -1;
1531
Victor Stinnerd3f08822012-05-29 12:57:52 +02001532 if (from_start < 0) {
1533 PyErr_SetString(PyExc_IndexError, "string index out of range");
1534 return -1;
1535 }
1536 if (to_start < 0) {
1537 PyErr_SetString(PyExc_IndexError, "string index out of range");
1538 return -1;
1539 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001540 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1541 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1542 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001543 "Cannot write %zi characters at %zi "
1544 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001545 how_many, to_start, PyUnicode_GET_LENGTH(to));
1546 return -1;
1547 }
1548
1549 if (how_many == 0)
1550 return 0;
1551
Victor Stinner488fa492011-12-12 00:01:39 +01001552 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001553 return -1;
1554
1555 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1556 if (err) {
1557 PyErr_Format(PyExc_SystemError,
1558 "Cannot copy %s characters "
1559 "into a string of %s characters",
1560 unicode_kind_name(from),
1561 unicode_kind_name(to));
1562 return -1;
1563 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001564 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001565}
1566
Victor Stinner17222162011-09-28 22:15:37 +02001567/* Find the maximum code point and count the number of surrogate pairs so a
1568 correct string length can be computed before converting a string to UCS4.
1569 This function counts single surrogates as a character and not as a pair.
1570
1571 Return 0 on success, or -1 on error. */
1572static int
1573find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1574 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001575{
1576 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001577 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001578
Victor Stinnerc53be962011-10-02 21:33:54 +02001579 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001580 *num_surrogates = 0;
1581 *maxchar = 0;
1582
1583 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001585 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1586 && (iter+1) < end
1587 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1588 {
1589 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1590 ++(*num_surrogates);
1591 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 }
1593 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001595 {
1596 ch = *iter;
1597 iter++;
1598 }
1599 if (ch > *maxchar) {
1600 *maxchar = ch;
1601 if (*maxchar > MAX_UNICODE) {
1602 PyErr_Format(PyExc_ValueError,
1603 "character U+%x is not in range [U+0000; U+10ffff]",
1604 ch);
1605 return -1;
1606 }
1607 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 }
1609 return 0;
1610}
1611
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001612int
1613_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001614{
1615 wchar_t *end;
1616 Py_UCS4 maxchar = 0;
1617 Py_ssize_t num_surrogates;
1618#if SIZEOF_WCHAR_T == 2
1619 Py_ssize_t length_wo_surrogates;
1620#endif
1621
Georg Brandl7597add2011-10-05 16:36:47 +02001622 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001623 strings were created using _PyObject_New() and where no canonical
1624 representation (the str field) has been set yet aka strings
1625 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001626 assert(_PyUnicode_CHECK(unicode));
1627 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001629 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001630 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001631 /* Actually, it should neither be interned nor be anything else: */
1632 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001634 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001635 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001636 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638
1639 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001640 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1641 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 PyErr_NoMemory();
1643 return -1;
1644 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001645 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646 _PyUnicode_WSTR(unicode), end,
1647 PyUnicode_1BYTE_DATA(unicode));
1648 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1649 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1650 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1651 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001652 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001653 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001654 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001655 }
1656 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001657 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001658 _PyUnicode_UTF8(unicode) = NULL;
1659 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 }
1661 PyObject_FREE(_PyUnicode_WSTR(unicode));
1662 _PyUnicode_WSTR(unicode) = NULL;
1663 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1664 }
1665 /* In this case we might have to convert down from 4-byte native
1666 wchar_t to 2-byte unicode. */
1667 else if (maxchar < 65536) {
1668 assert(num_surrogates == 0 &&
1669 "FindMaxCharAndNumSurrogatePairs() messed up");
1670
Victor Stinner506f5922011-09-28 22:34:18 +02001671#if SIZEOF_WCHAR_T == 2
1672 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001673 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001674 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1675 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1676 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8(unicode) = NULL;
1678 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001679#else
1680 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001681 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001682 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001683 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001684 PyErr_NoMemory();
1685 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686 }
Victor Stinner506f5922011-09-28 22:34:18 +02001687 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1688 _PyUnicode_WSTR(unicode), end,
1689 PyUnicode_2BYTE_DATA(unicode));
1690 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1691 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1692 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001695 PyObject_FREE(_PyUnicode_WSTR(unicode));
1696 _PyUnicode_WSTR(unicode) = NULL;
1697 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1698#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001699 }
1700 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1701 else {
1702#if SIZEOF_WCHAR_T == 2
1703 /* in case the native representation is 2-bytes, we need to allocate a
1704 new normalized 4-byte version. */
1705 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001706 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1707 PyErr_NoMemory();
1708 return -1;
1709 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001710 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1711 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001712 PyErr_NoMemory();
1713 return -1;
1714 }
1715 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1716 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001717 _PyUnicode_UTF8(unicode) = NULL;
1718 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001719 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1720 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001721 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 PyObject_FREE(_PyUnicode_WSTR(unicode));
1723 _PyUnicode_WSTR(unicode) = NULL;
1724 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1725#else
1726 assert(num_surrogates == 0);
1727
Victor Stinnerc3c74152011-10-02 20:39:55 +02001728 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001730 _PyUnicode_UTF8(unicode) = NULL;
1731 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1733#endif
1734 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1735 }
1736 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001737 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001738 return 0;
1739}
1740
Alexander Belopolsky40018472011-02-26 01:02:56 +00001741static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001742unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001743{
Walter Dörwald16807132007-05-25 13:52:07 +00001744 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001745 case SSTATE_NOT_INTERNED:
1746 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001747
Benjamin Peterson29060642009-01-31 22:14:21 +00001748 case SSTATE_INTERNED_MORTAL:
1749 /* revive dead object temporarily for DelItem */
1750 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001751 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001752 Py_FatalError(
1753 "deletion of interned string failed");
1754 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001755
Benjamin Peterson29060642009-01-31 22:14:21 +00001756 case SSTATE_INTERNED_IMMORTAL:
1757 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001758
Benjamin Peterson29060642009-01-31 22:14:21 +00001759 default:
1760 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001761 }
1762
Victor Stinner03490912011-10-03 23:45:12 +02001763 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001765 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001766 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001767 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1768 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001770 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001771}
1772
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001773#ifdef Py_DEBUG
1774static int
1775unicode_is_singleton(PyObject *unicode)
1776{
1777 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1778 if (unicode == unicode_empty)
1779 return 1;
1780 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1781 {
1782 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1783 if (ch < 256 && unicode_latin1[ch] == unicode)
1784 return 1;
1785 }
1786 return 0;
1787}
1788#endif
1789
Alexander Belopolsky40018472011-02-26 01:02:56 +00001790static int
Victor Stinner488fa492011-12-12 00:01:39 +01001791unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001792{
Victor Stinner488fa492011-12-12 00:01:39 +01001793 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001794 if (Py_REFCNT(unicode) != 1)
1795 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001796 if (_PyUnicode_HASH(unicode) != -1)
1797 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001798 if (PyUnicode_CHECK_INTERNED(unicode))
1799 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001800 if (!PyUnicode_CheckExact(unicode))
1801 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001802#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001803 /* singleton refcount is greater than 1 */
1804 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001805#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001806 return 1;
1807}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808
Victor Stinnerfe226c02011-10-03 03:52:20 +02001809static int
1810unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1811{
1812 PyObject *unicode;
1813 Py_ssize_t old_length;
1814
1815 assert(p_unicode != NULL);
1816 unicode = *p_unicode;
1817
1818 assert(unicode != NULL);
1819 assert(PyUnicode_Check(unicode));
1820 assert(0 <= length);
1821
Victor Stinner910337b2011-10-03 03:20:16 +02001822 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001823 old_length = PyUnicode_WSTR_LENGTH(unicode);
1824 else
1825 old_length = PyUnicode_GET_LENGTH(unicode);
1826 if (old_length == length)
1827 return 0;
1828
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001829 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001830 _Py_INCREF_UNICODE_EMPTY();
1831 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001832 return -1;
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001833 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001834 return 0;
1835 }
1836
Victor Stinner488fa492011-12-12 00:01:39 +01001837 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001838 PyObject *copy = resize_copy(unicode, length);
1839 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001840 return -1;
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +02001841 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001842 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001843 }
1844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001846 PyObject *new_unicode = resize_compact(unicode, length);
1847 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001848 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001849 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001850 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001851 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001852 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001853}
1854
Alexander Belopolsky40018472011-02-26 01:02:56 +00001855int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001856PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001857{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001858 PyObject *unicode;
1859 if (p_unicode == NULL) {
1860 PyErr_BadInternalCall();
1861 return -1;
1862 }
1863 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001864 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001865 {
1866 PyErr_BadInternalCall();
1867 return -1;
1868 }
1869 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001870}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001871
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001872/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001873
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001874 WARNING: The function doesn't copy the terminating null character and
1875 doesn't check the maximum character (may write a latin1 character in an
1876 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001877static void
1878unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1879 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001880{
1881 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1882 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001883 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001884
1885 switch (kind) {
1886 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001887 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001888#ifdef Py_DEBUG
1889 if (PyUnicode_IS_ASCII(unicode)) {
1890 Py_UCS4 maxchar = ucs1lib_find_max_char(
1891 (const Py_UCS1*)str,
1892 (const Py_UCS1*)str + len);
1893 assert(maxchar < 128);
1894 }
1895#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001896 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001897 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001898 }
1899 case PyUnicode_2BYTE_KIND: {
1900 Py_UCS2 *start = (Py_UCS2 *)data + index;
1901 Py_UCS2 *ucs2 = start;
1902 assert(index <= PyUnicode_GET_LENGTH(unicode));
1903
Victor Stinner184252a2012-06-16 02:57:41 +02001904 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001905 *ucs2 = (Py_UCS2)*str;
1906
1907 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001908 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001909 }
1910 default: {
1911 Py_UCS4 *start = (Py_UCS4 *)data + index;
1912 Py_UCS4 *ucs4 = start;
1913 assert(kind == PyUnicode_4BYTE_KIND);
1914 assert(index <= PyUnicode_GET_LENGTH(unicode));
1915
Victor Stinner184252a2012-06-16 02:57:41 +02001916 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001917 *ucs4 = (Py_UCS4)*str;
1918
1919 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001920 }
1921 }
1922}
1923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001924static PyObject*
1925get_latin1_char(unsigned char ch)
1926{
Victor Stinnera464fc12011-10-02 20:39:30 +02001927 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001928 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001929 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001930 if (!unicode)
1931 return NULL;
1932 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001933 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001934 unicode_latin1[ch] = unicode;
1935 }
1936 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001937 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001938}
1939
Victor Stinner985a82a2014-01-03 12:53:47 +01001940static PyObject*
1941unicode_char(Py_UCS4 ch)
1942{
1943 PyObject *unicode;
1944
1945 assert(ch <= MAX_UNICODE);
1946
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001947 if (ch < 256)
1948 return get_latin1_char(ch);
1949
Victor Stinner985a82a2014-01-03 12:53:47 +01001950 unicode = PyUnicode_New(1, ch);
1951 if (unicode == NULL)
1952 return NULL;
1953 switch (PyUnicode_KIND(unicode)) {
1954 case PyUnicode_1BYTE_KIND:
1955 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1956 break;
1957 case PyUnicode_2BYTE_KIND:
1958 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1959 break;
1960 default:
1961 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1962 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1963 }
1964 assert(_PyUnicode_CheckConsistency(unicode, 1));
1965 return unicode;
1966}
1967
Alexander Belopolsky40018472011-02-26 01:02:56 +00001968PyObject *
1969PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001970{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001971 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001972 Py_UCS4 maxchar = 0;
1973 Py_ssize_t num_surrogates;
1974
1975 if (u == NULL)
1976 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001977
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001978 /* If the Unicode data is known at construction time, we can apply
1979 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001981 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001982 if (size == 0)
1983 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 /* Single character Unicode objects in the Latin-1 range are
1986 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001987 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988 return get_latin1_char((unsigned char)*u);
1989
1990 /* If not empty and not single character, copy the Unicode data
1991 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001992 if (find_maxchar_surrogates(u, u + size,
1993 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return NULL;
1995
Victor Stinner8faf8212011-12-08 22:14:11 +01001996 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001997 if (!unicode)
1998 return NULL;
1999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 switch (PyUnicode_KIND(unicode)) {
2001 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002002 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2004 break;
2005 case PyUnicode_2BYTE_KIND:
2006#if Py_UNICODE_SIZE == 2
2007 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2008#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002009 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2011#endif
2012 break;
2013 case PyUnicode_4BYTE_KIND:
2014#if SIZEOF_WCHAR_T == 2
2015 /* This is the only case which has to process surrogates, thus
2016 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002017 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018#else
2019 assert(num_surrogates == 0);
2020 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2021#endif
2022 break;
2023 default:
2024 assert(0 && "Impossible state");
2025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002026
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002027 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002028}
2029
Alexander Belopolsky40018472011-02-26 01:02:56 +00002030PyObject *
2031PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002032{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002033 if (size < 0) {
2034 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002035 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002036 return NULL;
2037 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002038 if (u != NULL)
2039 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2040 else
2041 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002042}
2043
Alexander Belopolsky40018472011-02-26 01:02:56 +00002044PyObject *
2045PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002046{
2047 size_t size = strlen(u);
2048 if (size > PY_SSIZE_T_MAX) {
2049 PyErr_SetString(PyExc_OverflowError, "input too long");
2050 return NULL;
2051 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002052 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002053}
2054
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002055PyObject *
2056_PyUnicode_FromId(_Py_Identifier *id)
2057{
2058 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002059 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2060 strlen(id->string),
2061 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002062 if (!id->object)
2063 return NULL;
2064 PyUnicode_InternInPlace(&id->object);
2065 assert(!id->next);
2066 id->next = static_strings;
2067 static_strings = id;
2068 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002069 return id->object;
2070}
2071
2072void
2073_PyUnicode_ClearStaticStrings()
2074{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002075 _Py_Identifier *tmp, *s = static_strings;
2076 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002077 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002078 tmp = s->next;
2079 s->next = NULL;
2080 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002082 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002083}
2084
Benjamin Peterson0df54292012-03-26 14:50:32 -04002085/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002086
Victor Stinnerd3f08822012-05-29 12:57:52 +02002087PyObject*
2088_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002089{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002090 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002091 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002092 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002093#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002094 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002095#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002096 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002097 }
Victor Stinner785938e2011-12-11 20:09:03 +01002098 unicode = PyUnicode_New(size, 127);
2099 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002100 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002101 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2102 assert(_PyUnicode_CheckConsistency(unicode, 1));
2103 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002104}
2105
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002106static Py_UCS4
2107kind_maxchar_limit(unsigned int kind)
2108{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002109 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002110 case PyUnicode_1BYTE_KIND:
2111 return 0x80;
2112 case PyUnicode_2BYTE_KIND:
2113 return 0x100;
2114 case PyUnicode_4BYTE_KIND:
2115 return 0x10000;
2116 default:
2117 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002118 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002119 }
2120}
2121
Victor Stinnere6abb482012-05-02 01:15:40 +02002122Py_LOCAL_INLINE(Py_UCS4)
2123align_maxchar(Py_UCS4 maxchar)
2124{
2125 if (maxchar <= 127)
2126 return 127;
2127 else if (maxchar <= 255)
2128 return 255;
2129 else if (maxchar <= 65535)
2130 return 65535;
2131 else
2132 return MAX_UNICODE;
2133}
2134
Victor Stinner702c7342011-10-05 13:50:52 +02002135static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002136_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002137{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002138 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002140
Serhiy Storchaka678db842013-01-26 12:16:36 +02002141 if (size == 0)
2142 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002143 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002144 if (size == 1)
2145 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002146
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002147 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002148 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 if (!res)
2150 return NULL;
2151 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002152 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002153 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002154}
2155
Victor Stinnere57b1c02011-09-28 22:20:48 +02002156static PyObject*
2157_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158{
2159 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002160 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002161
Serhiy Storchaka678db842013-01-26 12:16:36 +02002162 if (size == 0)
2163 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002164 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002165 if (size == 1)
2166 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002167
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002168 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002169 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170 if (!res)
2171 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002172 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002174 else {
2175 _PyUnicode_CONVERT_BYTES(
2176 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2177 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002178 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002179 return res;
2180}
2181
Victor Stinnere57b1c02011-09-28 22:20:48 +02002182static PyObject*
2183_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184{
2185 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002186 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187
Serhiy Storchaka678db842013-01-26 12:16:36 +02002188 if (size == 0)
2189 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002190 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002191 if (size == 1)
2192 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002193
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002194 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002195 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002196 if (!res)
2197 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002198 if (max_char < 256)
2199 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2200 PyUnicode_1BYTE_DATA(res));
2201 else if (max_char < 0x10000)
2202 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2203 PyUnicode_2BYTE_DATA(res));
2204 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002206 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 return res;
2208}
2209
2210PyObject*
2211PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2212{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002213 if (size < 0) {
2214 PyErr_SetString(PyExc_ValueError, "size must be positive");
2215 return NULL;
2216 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002217 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002219 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002223 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002224 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002225 PyErr_SetString(PyExc_SystemError, "invalid kind");
2226 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002228}
2229
Victor Stinnerece58de2012-04-23 23:36:38 +02002230Py_UCS4
2231_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2232{
2233 enum PyUnicode_Kind kind;
2234 void *startptr, *endptr;
2235
2236 assert(PyUnicode_IS_READY(unicode));
2237 assert(0 <= start);
2238 assert(end <= PyUnicode_GET_LENGTH(unicode));
2239 assert(start <= end);
2240
2241 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2242 return PyUnicode_MAX_CHAR_VALUE(unicode);
2243
2244 if (start == end)
2245 return 127;
2246
Victor Stinner94d558b2012-04-27 22:26:58 +02002247 if (PyUnicode_IS_ASCII(unicode))
2248 return 127;
2249
Victor Stinnerece58de2012-04-23 23:36:38 +02002250 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002251 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002252 endptr = (char *)startptr + end * kind;
2253 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002254 switch(kind) {
2255 case PyUnicode_1BYTE_KIND:
2256 return ucs1lib_find_max_char(startptr, endptr);
2257 case PyUnicode_2BYTE_KIND:
2258 return ucs2lib_find_max_char(startptr, endptr);
2259 case PyUnicode_4BYTE_KIND:
2260 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002261 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002262 assert(0);
2263 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002264 }
2265}
2266
Victor Stinner25a4b292011-10-06 12:31:55 +02002267/* Ensure that a string uses the most efficient storage, if it is not the
2268 case: create a new string with of the right kind. Write NULL into *p_unicode
2269 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002270static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002271unicode_adjust_maxchar(PyObject **p_unicode)
2272{
2273 PyObject *unicode, *copy;
2274 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002275 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002276 unsigned int kind;
2277
2278 assert(p_unicode != NULL);
2279 unicode = *p_unicode;
2280 assert(PyUnicode_IS_READY(unicode));
2281 if (PyUnicode_IS_ASCII(unicode))
2282 return;
2283
2284 len = PyUnicode_GET_LENGTH(unicode);
2285 kind = PyUnicode_KIND(unicode);
2286 if (kind == PyUnicode_1BYTE_KIND) {
2287 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002288 max_char = ucs1lib_find_max_char(u, u + len);
2289 if (max_char >= 128)
2290 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002291 }
2292 else if (kind == PyUnicode_2BYTE_KIND) {
2293 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002294 max_char = ucs2lib_find_max_char(u, u + len);
2295 if (max_char >= 256)
2296 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002297 }
2298 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002299 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002300 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002301 max_char = ucs4lib_find_max_char(u, u + len);
2302 if (max_char >= 0x10000)
2303 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002304 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002305 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002306 if (copy != NULL)
2307 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002308 Py_DECREF(unicode);
2309 *p_unicode = copy;
2310}
2311
Victor Stinner034f6cf2011-09-30 02:26:44 +02002312PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002313_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002314{
Victor Stinner87af4f22011-11-21 23:03:47 +01002315 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002316 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002317
Victor Stinner034f6cf2011-09-30 02:26:44 +02002318 if (!PyUnicode_Check(unicode)) {
2319 PyErr_BadInternalCall();
2320 return NULL;
2321 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002322 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002323 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002324
Victor Stinner87af4f22011-11-21 23:03:47 +01002325 length = PyUnicode_GET_LENGTH(unicode);
2326 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002327 if (!copy)
2328 return NULL;
2329 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2330
Victor Stinner87af4f22011-11-21 23:03:47 +01002331 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2332 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002333 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002334 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002335}
2336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002337
Victor Stinnerbc603d12011-10-02 01:00:40 +02002338/* Widen Unicode objects to larger buffers. Don't write terminating null
2339 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002340
2341void*
2342_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2343{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002344 Py_ssize_t len;
2345 void *result;
2346 unsigned int skind;
2347
Benjamin Petersonbac79492012-01-14 13:34:47 -05002348 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002349 return NULL;
2350
2351 len = PyUnicode_GET_LENGTH(s);
2352 skind = PyUnicode_KIND(s);
2353 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002354 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002355 return NULL;
2356 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002357 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002358 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002359 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002360 if (!result)
2361 return PyErr_NoMemory();
2362 assert(skind == PyUnicode_1BYTE_KIND);
2363 _PyUnicode_CONVERT_BYTES(
2364 Py_UCS1, Py_UCS2,
2365 PyUnicode_1BYTE_DATA(s),
2366 PyUnicode_1BYTE_DATA(s) + len,
2367 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002368 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002369 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002370 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002371 if (!result)
2372 return PyErr_NoMemory();
2373 if (skind == PyUnicode_2BYTE_KIND) {
2374 _PyUnicode_CONVERT_BYTES(
2375 Py_UCS2, Py_UCS4,
2376 PyUnicode_2BYTE_DATA(s),
2377 PyUnicode_2BYTE_DATA(s) + len,
2378 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002380 else {
2381 assert(skind == PyUnicode_1BYTE_KIND);
2382 _PyUnicode_CONVERT_BYTES(
2383 Py_UCS1, Py_UCS4,
2384 PyUnicode_1BYTE_DATA(s),
2385 PyUnicode_1BYTE_DATA(s) + len,
2386 result);
2387 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002389 default:
2390 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 }
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394}
2395
2396static Py_UCS4*
2397as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2398 int copy_null)
2399{
2400 int kind;
2401 void *data;
2402 Py_ssize_t len, targetlen;
2403 if (PyUnicode_READY(string) == -1)
2404 return NULL;
2405 kind = PyUnicode_KIND(string);
2406 data = PyUnicode_DATA(string);
2407 len = PyUnicode_GET_LENGTH(string);
2408 targetlen = len;
2409 if (copy_null)
2410 targetlen++;
2411 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002412 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 if (!target) {
2414 PyErr_NoMemory();
2415 return NULL;
2416 }
2417 }
2418 else {
2419 if (targetsize < targetlen) {
2420 PyErr_Format(PyExc_SystemError,
2421 "string is longer than the buffer");
2422 if (copy_null && 0 < targetsize)
2423 target[0] = 0;
2424 return NULL;
2425 }
2426 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002427 if (kind == PyUnicode_1BYTE_KIND) {
2428 Py_UCS1 *start = (Py_UCS1 *) data;
2429 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002430 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002431 else if (kind == PyUnicode_2BYTE_KIND) {
2432 Py_UCS2 *start = (Py_UCS2 *) data;
2433 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2434 }
2435 else {
2436 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002437 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 if (copy_null)
2440 target[len] = 0;
2441 return target;
2442}
2443
2444Py_UCS4*
2445PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2446 int copy_null)
2447{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002448 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 PyErr_BadInternalCall();
2450 return NULL;
2451 }
2452 return as_ucs4(string, target, targetsize, copy_null);
2453}
2454
2455Py_UCS4*
2456PyUnicode_AsUCS4Copy(PyObject *string)
2457{
2458 return as_ucs4(string, NULL, 0, 1);
2459}
2460
2461#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002462
Alexander Belopolsky40018472011-02-26 01:02:56 +00002463PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002464PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002465{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002466 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002467 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002468 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002469 PyErr_BadInternalCall();
2470 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002471 }
2472
Martin v. Löwis790465f2008-04-05 20:41:37 +00002473 if (size == -1) {
2474 size = wcslen(w);
2475 }
2476
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002478}
2479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002481
Victor Stinner15a11362012-10-06 23:48:20 +02002482/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002483 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2484 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2485#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002486
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002487static int
2488unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2489 Py_ssize_t width, Py_ssize_t precision)
2490{
2491 Py_ssize_t length, fill, arglen;
2492 Py_UCS4 maxchar;
2493
2494 if (PyUnicode_READY(str) == -1)
2495 return -1;
2496
2497 length = PyUnicode_GET_LENGTH(str);
2498 if ((precision == -1 || precision >= length)
2499 && width <= length)
2500 return _PyUnicodeWriter_WriteStr(writer, str);
2501
2502 if (precision != -1)
2503 length = Py_MIN(precision, length);
2504
2505 arglen = Py_MAX(length, width);
2506 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2507 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2508 else
2509 maxchar = writer->maxchar;
2510
2511 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2512 return -1;
2513
2514 if (width > length) {
2515 fill = width - length;
2516 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2517 return -1;
2518 writer->pos += fill;
2519 }
2520
2521 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2522 str, 0, length);
2523 writer->pos += length;
2524 return 0;
2525}
2526
2527static int
2528unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2529 Py_ssize_t width, Py_ssize_t precision)
2530{
2531 /* UTF-8 */
2532 Py_ssize_t length;
2533 PyObject *unicode;
2534 int res;
2535
2536 length = strlen(str);
2537 if (precision != -1)
2538 length = Py_MIN(length, precision);
2539 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2540 if (unicode == NULL)
2541 return -1;
2542
2543 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2544 Py_DECREF(unicode);
2545 return res;
2546}
2547
Victor Stinner96865452011-03-01 23:44:09 +00002548static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002549unicode_fromformat_arg(_PyUnicodeWriter *writer,
2550 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002551{
Victor Stinnere215d962012-10-06 23:03:36 +02002552 const char *p;
2553 Py_ssize_t len;
2554 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002555 Py_ssize_t width;
2556 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002557 int longflag;
2558 int longlongflag;
2559 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002560 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002561
2562 p = f;
2563 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002564 zeropad = 0;
2565 if (*f == '0') {
2566 zeropad = 1;
2567 f++;
2568 }
Victor Stinner96865452011-03-01 23:44:09 +00002569
2570 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002571 width = -1;
2572 if (Py_ISDIGIT((unsigned)*f)) {
2573 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002574 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002575 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002576 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002577 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002578 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002579 return NULL;
2580 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002581 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002582 f++;
2583 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002584 }
2585 precision = -1;
2586 if (*f == '.') {
2587 f++;
2588 if (Py_ISDIGIT((unsigned)*f)) {
2589 precision = (*f - '0');
2590 f++;
2591 while (Py_ISDIGIT((unsigned)*f)) {
2592 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2593 PyErr_SetString(PyExc_ValueError,
2594 "precision too big");
2595 return NULL;
2596 }
2597 precision = (precision * 10) + (*f - '0');
2598 f++;
2599 }
2600 }
Victor Stinner96865452011-03-01 23:44:09 +00002601 if (*f == '%') {
2602 /* "%.3%s" => f points to "3" */
2603 f--;
2604 }
2605 }
2606 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002607 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002608 f--;
2609 }
Victor Stinner96865452011-03-01 23:44:09 +00002610
2611 /* Handle %ld, %lu, %lld and %llu. */
2612 longflag = 0;
2613 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002614 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002615 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002616 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002617 longflag = 1;
2618 ++f;
2619 }
2620#ifdef HAVE_LONG_LONG
2621 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002622 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002623 longlongflag = 1;
2624 f += 2;
2625 }
2626#endif
2627 }
2628 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002629 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002630 size_tflag = 1;
2631 ++f;
2632 }
Victor Stinnere215d962012-10-06 23:03:36 +02002633
2634 if (f[1] == '\0')
2635 writer->overallocate = 0;
2636
2637 switch (*f) {
2638 case 'c':
2639 {
2640 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002641 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002642 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002643 "character argument not in range(0x110000)");
2644 return NULL;
2645 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002646 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002647 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002648 break;
2649 }
2650
2651 case 'i':
2652 case 'd':
2653 case 'u':
2654 case 'x':
2655 {
2656 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002657 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002658 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002659
2660 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002661 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002662 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002663 va_arg(*vargs, unsigned long));
2664#ifdef HAVE_LONG_LONG
2665 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002666 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002667 va_arg(*vargs, unsigned PY_LONG_LONG));
2668#endif
2669 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002670 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002671 va_arg(*vargs, size_t));
2672 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002673 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002674 va_arg(*vargs, unsigned int));
2675 }
2676 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002678 }
2679 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002680 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002681 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002682 va_arg(*vargs, long));
2683#ifdef HAVE_LONG_LONG
2684 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002685 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002686 va_arg(*vargs, PY_LONG_LONG));
2687#endif
2688 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002689 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002690 va_arg(*vargs, Py_ssize_t));
2691 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002692 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002693 va_arg(*vargs, int));
2694 }
2695 assert(len >= 0);
2696
Victor Stinnere215d962012-10-06 23:03:36 +02002697 if (precision < len)
2698 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002699
2700 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002701 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2702 return NULL;
2703
Victor Stinnere215d962012-10-06 23:03:36 +02002704 if (width > precision) {
2705 Py_UCS4 fillchar;
2706 fill = width - precision;
2707 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002708 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2709 return NULL;
2710 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002711 }
Victor Stinner15a11362012-10-06 23:48:20 +02002712 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002713 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002714 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2715 return NULL;
2716 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002717 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002718
Victor Stinner4a587072013-11-19 12:54:53 +01002719 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2720 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002721 break;
2722 }
2723
2724 case 'p':
2725 {
2726 char number[MAX_LONG_LONG_CHARS];
2727
2728 len = sprintf(number, "%p", va_arg(*vargs, void*));
2729 assert(len >= 0);
2730
2731 /* %p is ill-defined: ensure leading 0x. */
2732 if (number[1] == 'X')
2733 number[1] = 'x';
2734 else if (number[1] != 'x') {
2735 memmove(number + 2, number,
2736 strlen(number) + 1);
2737 number[0] = '0';
2738 number[1] = 'x';
2739 len += 2;
2740 }
2741
Victor Stinner4a587072013-11-19 12:54:53 +01002742 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002743 return NULL;
2744 break;
2745 }
2746
2747 case 's':
2748 {
2749 /* UTF-8 */
2750 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002751 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002752 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002753 break;
2754 }
2755
2756 case 'U':
2757 {
2758 PyObject *obj = va_arg(*vargs, PyObject *);
2759 assert(obj && _PyUnicode_CHECK(obj));
2760
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002761 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002762 return NULL;
2763 break;
2764 }
2765
2766 case 'V':
2767 {
2768 PyObject *obj = va_arg(*vargs, PyObject *);
2769 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002770 if (obj) {
2771 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 }
2775 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002776 assert(str != NULL);
2777 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002778 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002779 }
2780 break;
2781 }
2782
2783 case 'S':
2784 {
2785 PyObject *obj = va_arg(*vargs, PyObject *);
2786 PyObject *str;
2787 assert(obj);
2788 str = PyObject_Str(obj);
2789 if (!str)
2790 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002791 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002792 Py_DECREF(str);
2793 return NULL;
2794 }
2795 Py_DECREF(str);
2796 break;
2797 }
2798
2799 case 'R':
2800 {
2801 PyObject *obj = va_arg(*vargs, PyObject *);
2802 PyObject *repr;
2803 assert(obj);
2804 repr = PyObject_Repr(obj);
2805 if (!repr)
2806 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002807 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002808 Py_DECREF(repr);
2809 return NULL;
2810 }
2811 Py_DECREF(repr);
2812 break;
2813 }
2814
2815 case 'A':
2816 {
2817 PyObject *obj = va_arg(*vargs, PyObject *);
2818 PyObject *ascii;
2819 assert(obj);
2820 ascii = PyObject_ASCII(obj);
2821 if (!ascii)
2822 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002823 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002824 Py_DECREF(ascii);
2825 return NULL;
2826 }
2827 Py_DECREF(ascii);
2828 break;
2829 }
2830
2831 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002832 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002833 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002834 break;
2835
2836 default:
2837 /* if we stumble upon an unknown formatting code, copy the rest
2838 of the format string to the output string. (we cannot just
2839 skip the code, since there's no way to know what's in the
2840 argument list) */
2841 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002842 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002843 return NULL;
2844 f = p+len;
2845 return f;
2846 }
2847
2848 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002849 return f;
2850}
2851
Walter Dörwaldd2034312007-05-18 16:29:38 +00002852PyObject *
2853PyUnicode_FromFormatV(const char *format, va_list vargs)
2854{
Victor Stinnere215d962012-10-06 23:03:36 +02002855 va_list vargs2;
2856 const char *f;
2857 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002858
Victor Stinner8f674cc2013-04-17 23:02:17 +02002859 _PyUnicodeWriter_Init(&writer);
2860 writer.min_length = strlen(format) + 100;
2861 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002862
2863 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2864 Copy it to be able to pass a reference to a subfunction. */
2865 Py_VA_COPY(vargs2, vargs);
2866
2867 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002868 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002869 f = unicode_fromformat_arg(&writer, f, &vargs2);
2870 if (f == NULL)
2871 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002873 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002874 const char *p;
2875 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002876
Victor Stinnere215d962012-10-06 23:03:36 +02002877 p = f;
2878 do
2879 {
2880 if ((unsigned char)*p > 127) {
2881 PyErr_Format(PyExc_ValueError,
2882 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2883 "string, got a non-ASCII byte: 0x%02x",
2884 (unsigned char)*p);
2885 return NULL;
2886 }
2887 p++;
2888 }
2889 while (*p != '\0' && *p != '%');
2890 len = p - f;
2891
2892 if (*p == '\0')
2893 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002894
2895 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002896 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002897
2898 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002899 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002900 }
Victor Stinnere215d962012-10-06 23:03:36 +02002901 return _PyUnicodeWriter_Finish(&writer);
2902
2903 fail:
2904 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002905 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002906}
2907
Walter Dörwaldd2034312007-05-18 16:29:38 +00002908PyObject *
2909PyUnicode_FromFormat(const char *format, ...)
2910{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002911 PyObject* ret;
2912 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002913
2914#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002915 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002916#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002919 ret = PyUnicode_FromFormatV(format, vargs);
2920 va_end(vargs);
2921 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002922}
2923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002924#ifdef HAVE_WCHAR_H
2925
Victor Stinner5593d8a2010-10-02 11:11:27 +00002926/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2927 convert a Unicode object to a wide character string.
2928
Victor Stinnerd88d9832011-09-06 02:00:05 +02002929 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002930 character) required to convert the unicode object. Ignore size argument.
2931
Victor Stinnerd88d9832011-09-06 02:00:05 +02002932 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002933 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002934 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002935static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002936unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002937 wchar_t *w,
2938 Py_ssize_t size)
2939{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002940 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002941 const wchar_t *wstr;
2942
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002943 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002944 if (wstr == NULL)
2945 return -1;
2946
Victor Stinner5593d8a2010-10-02 11:11:27 +00002947 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948 if (size > res)
2949 size = res + 1;
2950 else
2951 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002953 return res;
2954 }
2955 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002956 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002957}
2958
2959Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002960PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002961 wchar_t *w,
2962 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963{
2964 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002965 PyErr_BadInternalCall();
2966 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002967 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002968 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002969}
2970
Victor Stinner137c34c2010-09-29 10:25:54 +00002971wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002972PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002973 Py_ssize_t *size)
2974{
2975 wchar_t* buffer;
2976 Py_ssize_t buflen;
2977
2978 if (unicode == NULL) {
2979 PyErr_BadInternalCall();
2980 return NULL;
2981 }
2982
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002983 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002984 if (buflen == -1)
2985 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002986 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002987 if (buffer == NULL) {
2988 PyErr_NoMemory();
2989 return NULL;
2990 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002991 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002992 if (buflen == -1) {
2993 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002994 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002995 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002996 if (size != NULL)
2997 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 return buffer;
2999}
3000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003001#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003002
Alexander Belopolsky40018472011-02-26 01:02:56 +00003003PyObject *
3004PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003005{
Victor Stinner8faf8212011-12-08 22:14:11 +01003006 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003007 PyErr_SetString(PyExc_ValueError,
3008 "chr() arg not in range(0x110000)");
3009 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003010 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003011
Victor Stinner985a82a2014-01-03 12:53:47 +01003012 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003013}
3014
Alexander Belopolsky40018472011-02-26 01:02:56 +00003015PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003016PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003018 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003020 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003021 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003022 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003023 Py_INCREF(obj);
3024 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 }
3026 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003027 /* For a Unicode subtype that's not a Unicode object,
3028 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003029 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003030 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003031 PyErr_Format(PyExc_TypeError,
3032 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003033 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003034 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003035}
3036
Alexander Belopolsky40018472011-02-26 01:02:56 +00003037PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003038PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003039 const char *encoding,
3040 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003041{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003042 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003043 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003044
Guido van Rossumd57fd912000-03-10 22:53:23 +00003045 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 PyErr_BadInternalCall();
3047 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003048 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003049
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003050 /* Decoding bytes objects is the most common case and should be fast */
3051 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003052 if (PyBytes_GET_SIZE(obj) == 0)
3053 _Py_RETURN_UNICODE_EMPTY();
3054 v = PyUnicode_Decode(
3055 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3056 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 return v;
3058 }
3059
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003060 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003061 PyErr_SetString(PyExc_TypeError,
3062 "decoding str is not supported");
3063 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003064 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003065
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003066 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3067 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3068 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02003069 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003070 Py_TYPE(obj)->tp_name);
3071 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003072 }
Tim Petersced69f82003-09-16 20:30:58 +00003073
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003074 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003075 PyBuffer_Release(&buffer);
3076 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003078
Serhiy Storchaka05997252013-01-26 12:14:02 +02003079 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003080 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003081 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003082}
3083
Victor Stinner600d3be2010-06-10 12:00:55 +00003084/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00003085 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
3086 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003087int
3088_Py_normalize_encoding(const char *encoding,
3089 char *lower,
3090 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003091{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003092 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003093 char *l;
3094 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003095
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003096 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01003097 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01003098 if (lower_len < 6)
3099 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04003100 strcpy(lower, "utf-8");
3101 return 1;
3102 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003103 e = encoding;
3104 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003105 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00003106 while (*e) {
3107 if (l == l_end)
3108 return 0;
David Malcolm96960882010-11-05 17:23:41 +00003109 if (Py_ISUPPER(*e)) {
3110 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003111 }
3112 else if (*e == '_') {
3113 *l++ = '-';
3114 e++;
3115 }
3116 else {
3117 *l++ = *e++;
3118 }
3119 }
3120 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003121 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003122}
3123
Alexander Belopolsky40018472011-02-26 01:02:56 +00003124PyObject *
3125PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003126 Py_ssize_t size,
3127 const char *encoding,
3128 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003129{
3130 PyObject *buffer = NULL, *unicode;
3131 Py_buffer info;
3132 char lower[11]; /* Enough for any encoding shortcut */
3133
Fred Drakee4315f52000-05-09 19:53:39 +00003134 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003135 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003136 if ((strcmp(lower, "utf-8") == 0) ||
3137 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003138 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003139 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003140 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003141 (strcmp(lower, "iso-8859-1") == 0) ||
3142 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003143 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003144#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003145 else if (strcmp(lower, "mbcs") == 0)
3146 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003147#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003148 else if (strcmp(lower, "ascii") == 0)
3149 return PyUnicode_DecodeASCII(s, size, errors);
3150 else if (strcmp(lower, "utf-16") == 0)
3151 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3152 else if (strcmp(lower, "utf-32") == 0)
3153 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3154 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003155
3156 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003157 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003158 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003159 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003160 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003161 if (buffer == NULL)
3162 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003163 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003164 if (unicode == NULL)
3165 goto onError;
3166 if (!PyUnicode_Check(unicode)) {
3167 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003168 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3169 "use codecs.decode() to decode to arbitrary types",
3170 encoding,
3171 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003172 Py_DECREF(unicode);
3173 goto onError;
3174 }
3175 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003176 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003177
Benjamin Peterson29060642009-01-31 22:14:21 +00003178 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003179 Py_XDECREF(buffer);
3180 return NULL;
3181}
3182
Alexander Belopolsky40018472011-02-26 01:02:56 +00003183PyObject *
3184PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003185 const char *encoding,
3186 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003187{
3188 PyObject *v;
3189
3190 if (!PyUnicode_Check(unicode)) {
3191 PyErr_BadArgument();
3192 goto onError;
3193 }
3194
3195 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003196 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003197
3198 /* Decode via the codec registry */
3199 v = PyCodec_Decode(unicode, encoding, errors);
3200 if (v == NULL)
3201 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003202 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003203
Benjamin Peterson29060642009-01-31 22:14:21 +00003204 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003205 return NULL;
3206}
3207
Alexander Belopolsky40018472011-02-26 01:02:56 +00003208PyObject *
3209PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003210 const char *encoding,
3211 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003212{
3213 PyObject *v;
3214
3215 if (!PyUnicode_Check(unicode)) {
3216 PyErr_BadArgument();
3217 goto onError;
3218 }
3219
3220 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003221 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003222
3223 /* Decode via the codec registry */
3224 v = PyCodec_Decode(unicode, encoding, errors);
3225 if (v == NULL)
3226 goto onError;
3227 if (!PyUnicode_Check(v)) {
3228 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003229 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3230 "use codecs.decode() to decode to arbitrary types",
3231 encoding,
3232 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003233 Py_DECREF(v);
3234 goto onError;
3235 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003236 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003237
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003239 return NULL;
3240}
3241
Alexander Belopolsky40018472011-02-26 01:02:56 +00003242PyObject *
3243PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003244 Py_ssize_t size,
3245 const char *encoding,
3246 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003247{
3248 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003249
Guido van Rossumd57fd912000-03-10 22:53:23 +00003250 unicode = PyUnicode_FromUnicode(s, size);
3251 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003252 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003253 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3254 Py_DECREF(unicode);
3255 return v;
3256}
3257
Alexander Belopolsky40018472011-02-26 01:02:56 +00003258PyObject *
3259PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003260 const char *encoding,
3261 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003262{
3263 PyObject *v;
3264
3265 if (!PyUnicode_Check(unicode)) {
3266 PyErr_BadArgument();
3267 goto onError;
3268 }
3269
3270 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003271 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003272
3273 /* Encode via the codec registry */
3274 v = PyCodec_Encode(unicode, encoding, errors);
3275 if (v == NULL)
3276 goto onError;
3277 return v;
3278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003280 return NULL;
3281}
3282
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003283static size_t
3284wcstombs_errorpos(const wchar_t *wstr)
3285{
3286 size_t len;
3287#if SIZEOF_WCHAR_T == 2
3288 wchar_t buf[3];
3289#else
3290 wchar_t buf[2];
3291#endif
3292 char outbuf[MB_LEN_MAX];
3293 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003294
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003295#if SIZEOF_WCHAR_T == 2
3296 buf[2] = 0;
3297#else
3298 buf[1] = 0;
3299#endif
3300 start = wstr;
3301 while (*wstr != L'\0')
3302 {
3303 previous = wstr;
3304#if SIZEOF_WCHAR_T == 2
3305 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3306 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3307 {
3308 buf[0] = wstr[0];
3309 buf[1] = wstr[1];
3310 wstr += 2;
3311 }
3312 else {
3313 buf[0] = *wstr;
3314 buf[1] = 0;
3315 wstr++;
3316 }
3317#else
3318 buf[0] = *wstr;
3319 wstr++;
3320#endif
3321 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003322 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003323 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003324 }
3325
3326 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003327 return 0;
3328}
3329
Victor Stinner1b579672011-12-17 05:47:23 +01003330static int
3331locale_error_handler(const char *errors, int *surrogateescape)
3332{
Victor Stinner50149202015-09-22 00:26:54 +02003333 _Py_error_handler error_handler = get_error_handler(errors);
3334 switch (error_handler)
3335 {
3336 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003337 *surrogateescape = 0;
3338 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003339 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003340 *surrogateescape = 1;
3341 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003342 default:
3343 PyErr_Format(PyExc_ValueError,
3344 "only 'strict' and 'surrogateescape' error handlers "
3345 "are supported, not '%s'",
3346 errors);
3347 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003348 }
Victor Stinner1b579672011-12-17 05:47:23 +01003349}
3350
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003351PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003352PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003353{
3354 Py_ssize_t wlen, wlen2;
3355 wchar_t *wstr;
3356 PyObject *bytes = NULL;
3357 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003358 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003359 PyObject *exc;
3360 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003361 int surrogateescape;
3362
3363 if (locale_error_handler(errors, &surrogateescape) < 0)
3364 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003365
3366 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3367 if (wstr == NULL)
3368 return NULL;
3369
3370 wlen2 = wcslen(wstr);
3371 if (wlen2 != wlen) {
3372 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003373 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return NULL;
3375 }
3376
3377 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003378 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003379 char *str;
3380
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003381 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003382 if (str == NULL) {
3383 if (error_pos == (size_t)-1) {
3384 PyErr_NoMemory();
3385 PyMem_Free(wstr);
3386 return NULL;
3387 }
3388 else {
3389 goto encode_error;
3390 }
3391 }
3392 PyMem_Free(wstr);
3393
3394 bytes = PyBytes_FromString(str);
3395 PyMem_Free(str);
3396 }
3397 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003398 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003399 size_t len, len2;
3400
3401 len = wcstombs(NULL, wstr, 0);
3402 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003403 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003404 goto encode_error;
3405 }
3406
3407 bytes = PyBytes_FromStringAndSize(NULL, len);
3408 if (bytes == NULL) {
3409 PyMem_Free(wstr);
3410 return NULL;
3411 }
3412
3413 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3414 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003415 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003416 goto encode_error;
3417 }
3418 PyMem_Free(wstr);
3419 }
3420 return bytes;
3421
3422encode_error:
3423 errmsg = strerror(errno);
3424 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003425
3426 if (error_pos == (size_t)-1)
3427 error_pos = wcstombs_errorpos(wstr);
3428
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003429 PyMem_Free(wstr);
3430 Py_XDECREF(bytes);
3431
Victor Stinner2f197072011-12-17 07:08:30 +01003432 if (errmsg != NULL) {
3433 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003434 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003435 if (wstr != NULL) {
3436 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003437 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003438 } else
3439 errmsg = NULL;
3440 }
3441 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003442 reason = PyUnicode_FromString(
3443 "wcstombs() encountered an unencodable "
3444 "wide character");
3445 if (reason == NULL)
3446 return NULL;
3447
3448 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3449 "locale", unicode,
3450 (Py_ssize_t)error_pos,
3451 (Py_ssize_t)(error_pos+1),
3452 reason);
3453 Py_DECREF(reason);
3454 if (exc != NULL) {
3455 PyCodec_StrictErrors(exc);
3456 Py_XDECREF(exc);
3457 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003458 return NULL;
3459}
3460
Victor Stinnerad158722010-10-27 00:25:46 +00003461PyObject *
3462PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003463{
Victor Stinner99b95382011-07-04 14:23:54 +02003464#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003465 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003466#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003467 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003468#else
Victor Stinner793b5312011-04-27 00:24:21 +02003469 PyInterpreterState *interp = PyThreadState_GET()->interp;
3470 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3471 cannot use it to encode and decode filenames before it is loaded. Load
3472 the Python codec requires to encode at least its own filename. Use the C
3473 version of the locale codec until the codec registry is initialized and
3474 the Python codec is loaded.
3475
3476 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3477 cannot only rely on it: check also interp->fscodec_initialized for
3478 subinterpreters. */
3479 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003480 return PyUnicode_AsEncodedString(unicode,
3481 Py_FileSystemDefaultEncoding,
3482 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003483 }
3484 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003485 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003486 }
Victor Stinnerad158722010-10-27 00:25:46 +00003487#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003488}
3489
Alexander Belopolsky40018472011-02-26 01:02:56 +00003490PyObject *
3491PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003492 const char *encoding,
3493 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003494{
3495 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003496 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003497
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 if (!PyUnicode_Check(unicode)) {
3499 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003500 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003501 }
Fred Drakee4315f52000-05-09 19:53:39 +00003502
Fred Drakee4315f52000-05-09 19:53:39 +00003503 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003504 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003505 if ((strcmp(lower, "utf-8") == 0) ||
3506 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003507 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003508 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003509 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003510 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003511 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003512 }
Victor Stinner37296e82010-06-10 13:36:23 +00003513 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003514 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003515 (strcmp(lower, "iso-8859-1") == 0) ||
3516 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003518#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003519 else if (strcmp(lower, "mbcs") == 0)
3520 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003521#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003522 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003523 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003525
3526 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003527 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003529 return NULL;
3530
3531 /* The normal path */
3532 if (PyBytes_Check(v))
3533 return v;
3534
3535 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003536 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003537 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003538 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003539
3540 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003541 "encoder %s returned bytearray instead of bytes; "
3542 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003543 encoding);
3544 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003545 Py_DECREF(v);
3546 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003547 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003548
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003549 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3550 Py_DECREF(v);
3551 return b;
3552 }
3553
3554 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003555 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3556 "use codecs.encode() to encode to arbitrary types",
3557 encoding,
3558 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003559 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003560 return NULL;
3561}
3562
Alexander Belopolsky40018472011-02-26 01:02:56 +00003563PyObject *
3564PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003565 const char *encoding,
3566 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003567{
3568 PyObject *v;
3569
3570 if (!PyUnicode_Check(unicode)) {
3571 PyErr_BadArgument();
3572 goto onError;
3573 }
3574
3575 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003576 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003577
3578 /* Encode via the codec registry */
3579 v = PyCodec_Encode(unicode, encoding, errors);
3580 if (v == NULL)
3581 goto onError;
3582 if (!PyUnicode_Check(v)) {
3583 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003584 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3585 "use codecs.encode() to encode to arbitrary types",
3586 encoding,
3587 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003588 Py_DECREF(v);
3589 goto onError;
3590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003591 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003592
Benjamin Peterson29060642009-01-31 22:14:21 +00003593 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003594 return NULL;
3595}
3596
Victor Stinner2f197072011-12-17 07:08:30 +01003597static size_t
3598mbstowcs_errorpos(const char *str, size_t len)
3599{
3600#ifdef HAVE_MBRTOWC
3601 const char *start = str;
3602 mbstate_t mbs;
3603 size_t converted;
3604 wchar_t ch;
3605
3606 memset(&mbs, 0, sizeof mbs);
3607 while (len)
3608 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003609 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003610 if (converted == 0)
3611 /* Reached end of string */
3612 break;
3613 if (converted == (size_t)-1 || converted == (size_t)-2) {
3614 /* Conversion error or incomplete character */
3615 return str - start;
3616 }
3617 else {
3618 str += converted;
3619 len -= converted;
3620 }
3621 }
3622 /* failed to find the undecodable byte sequence */
3623 return 0;
3624#endif
3625 return 0;
3626}
3627
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003628PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003629PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003630 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003631{
3632 wchar_t smallbuf[256];
3633 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3634 wchar_t *wstr;
3635 size_t wlen, wlen2;
3636 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003637 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003638 size_t error_pos;
3639 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003640 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3641 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003642
3643 if (locale_error_handler(errors, &surrogateescape) < 0)
3644 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003645
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003646 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3647 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003648 return NULL;
3649 }
3650
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003651 if (surrogateescape) {
3652 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003653 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003654 if (wstr == NULL) {
3655 if (wlen == (size_t)-1)
3656 PyErr_NoMemory();
3657 else
3658 PyErr_SetFromErrno(PyExc_OSError);
3659 return NULL;
3660 }
3661
3662 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003663 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003664 }
3665 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003666 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003667#ifndef HAVE_BROKEN_MBSTOWCS
3668 wlen = mbstowcs(NULL, str, 0);
3669#else
3670 wlen = len;
3671#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003672 if (wlen == (size_t)-1)
3673 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003674 if (wlen+1 <= smallbuf_len) {
3675 wstr = smallbuf;
3676 }
3677 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003678 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003679 if (!wstr)
3680 return PyErr_NoMemory();
3681 }
3682
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003683 wlen2 = mbstowcs(wstr, str, wlen+1);
3684 if (wlen2 == (size_t)-1) {
3685 if (wstr != smallbuf)
3686 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003687 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003688 }
3689#ifdef HAVE_BROKEN_MBSTOWCS
3690 assert(wlen2 == wlen);
3691#endif
3692 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3693 if (wstr != smallbuf)
3694 PyMem_Free(wstr);
3695 }
3696 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003697
3698decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003699 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003700 errmsg = strerror(errno);
3701 assert(errmsg != NULL);
3702
3703 error_pos = mbstowcs_errorpos(str, len);
3704 if (errmsg != NULL) {
3705 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003706 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003707 if (wstr != NULL) {
3708 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003709 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003710 }
Victor Stinner2f197072011-12-17 07:08:30 +01003711 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003712 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003713 reason = PyUnicode_FromString(
3714 "mbstowcs() encountered an invalid multibyte sequence");
3715 if (reason == NULL)
3716 return NULL;
3717
3718 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3719 "locale", str, len,
3720 (Py_ssize_t)error_pos,
3721 (Py_ssize_t)(error_pos+1),
3722 reason);
3723 Py_DECREF(reason);
3724 if (exc != NULL) {
3725 PyCodec_StrictErrors(exc);
3726 Py_XDECREF(exc);
3727 }
3728 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003729}
3730
3731PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003732PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003733{
3734 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003735 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003736}
3737
3738
3739PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003740PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003741 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003742 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3743}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003744
Christian Heimes5894ba72007-11-04 11:43:14 +00003745PyObject*
3746PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3747{
Victor Stinner99b95382011-07-04 14:23:54 +02003748#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003749 return PyUnicode_DecodeMBCS(s, size, NULL);
3750#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003751 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003752#else
Victor Stinner793b5312011-04-27 00:24:21 +02003753 PyInterpreterState *interp = PyThreadState_GET()->interp;
3754 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3755 cannot use it to encode and decode filenames before it is loaded. Load
3756 the Python codec requires to encode at least its own filename. Use the C
3757 version of the locale codec until the codec registry is initialized and
3758 the Python codec is loaded.
3759
3760 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3761 cannot only rely on it: check also interp->fscodec_initialized for
3762 subinterpreters. */
3763 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003764 return PyUnicode_Decode(s, size,
3765 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003766 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003767 }
3768 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003769 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003770 }
Victor Stinnerad158722010-10-27 00:25:46 +00003771#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003772}
3773
Martin v. Löwis011e8422009-05-05 04:43:17 +00003774
3775int
3776PyUnicode_FSConverter(PyObject* arg, void* addr)
3777{
3778 PyObject *output = NULL;
3779 Py_ssize_t size;
3780 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003781 if (arg == NULL) {
3782 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003783 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003784 return 1;
3785 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003786 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003787 output = arg;
3788 Py_INCREF(output);
3789 }
3790 else {
3791 arg = PyUnicode_FromObject(arg);
3792 if (!arg)
3793 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003794 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003795 Py_DECREF(arg);
3796 if (!output)
3797 return 0;
3798 if (!PyBytes_Check(output)) {
3799 Py_DECREF(output);
3800 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3801 return 0;
3802 }
3803 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003804 size = PyBytes_GET_SIZE(output);
3805 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003806 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003807 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003808 Py_DECREF(output);
3809 return 0;
3810 }
3811 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003812 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003813}
3814
3815
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003816int
3817PyUnicode_FSDecoder(PyObject* arg, void* addr)
3818{
3819 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003820 if (arg == NULL) {
3821 Py_DECREF(*(PyObject**)addr);
3822 return 1;
3823 }
3824 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003825 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003827 output = arg;
3828 Py_INCREF(output);
3829 }
3830 else {
3831 arg = PyBytes_FromObject(arg);
3832 if (!arg)
3833 return 0;
3834 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3835 PyBytes_GET_SIZE(arg));
3836 Py_DECREF(arg);
3837 if (!output)
3838 return 0;
3839 if (!PyUnicode_Check(output)) {
3840 Py_DECREF(output);
3841 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3842 return 0;
3843 }
3844 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003845 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003846 Py_DECREF(output);
3847 return 0;
3848 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003850 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003851 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003852 Py_DECREF(output);
3853 return 0;
3854 }
3855 *(PyObject**)addr = output;
3856 return Py_CLEANUP_SUPPORTED;
3857}
3858
3859
Martin v. Löwis5b222132007-06-10 09:51:05 +00003860char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003862{
Christian Heimesf3863112007-11-22 07:46:41 +00003863 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003864
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003865 if (!PyUnicode_Check(unicode)) {
3866 PyErr_BadArgument();
3867 return NULL;
3868 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003869 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003870 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003872 if (PyUnicode_UTF8(unicode) == NULL) {
3873 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3875 if (bytes == NULL)
3876 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3878 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003879 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880 Py_DECREF(bytes);
3881 return NULL;
3882 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3884 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3885 PyBytes_AS_STRING(bytes),
3886 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887 Py_DECREF(bytes);
3888 }
3889
3890 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003891 *psize = PyUnicode_UTF8_LENGTH(unicode);
3892 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003893}
3894
3895char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003898 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3899}
3900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003901Py_UNICODE *
3902PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3903{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003904 const unsigned char *one_byte;
3905#if SIZEOF_WCHAR_T == 4
3906 const Py_UCS2 *two_bytes;
3907#else
3908 const Py_UCS4 *four_bytes;
3909 const Py_UCS4 *ucs4_end;
3910 Py_ssize_t num_surrogates;
3911#endif
3912 wchar_t *w;
3913 wchar_t *wchar_end;
3914
3915 if (!PyUnicode_Check(unicode)) {
3916 PyErr_BadArgument();
3917 return NULL;
3918 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003919 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003921 assert(_PyUnicode_KIND(unicode) != 0);
3922 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003924 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003925#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003926 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3927 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003928 num_surrogates = 0;
3929
3930 for (; four_bytes < ucs4_end; ++four_bytes) {
3931 if (*four_bytes > 0xFFFF)
3932 ++num_surrogates;
3933 }
3934
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003935 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3936 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3937 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 PyErr_NoMemory();
3939 return NULL;
3940 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003942
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003943 w = _PyUnicode_WSTR(unicode);
3944 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3945 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3947 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003948 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003950 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3951 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952 }
3953 else
3954 *w = *four_bytes;
3955
3956 if (w > wchar_end) {
3957 assert(0 && "Miscalculated string end");
3958 }
3959 }
3960 *w = 0;
3961#else
3962 /* sizeof(wchar_t) == 4 */
3963 Py_FatalError("Impossible unicode object state, wstr and str "
3964 "should share memory already.");
3965 return NULL;
3966#endif
3967 }
3968 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003969 if ((size_t)_PyUnicode_LENGTH(unicode) >
3970 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3971 PyErr_NoMemory();
3972 return NULL;
3973 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003974 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3975 (_PyUnicode_LENGTH(unicode) + 1));
3976 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977 PyErr_NoMemory();
3978 return NULL;
3979 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003980 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3981 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3982 w = _PyUnicode_WSTR(unicode);
3983 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003985 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3986 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 for (; w < wchar_end; ++one_byte, ++w)
3988 *w = *one_byte;
3989 /* null-terminate the wstr */
3990 *w = 0;
3991 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003992 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003994 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995 for (; w < wchar_end; ++two_bytes, ++w)
3996 *w = *two_bytes;
3997 /* null-terminate the wstr */
3998 *w = 0;
3999#else
4000 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004001 PyObject_FREE(_PyUnicode_WSTR(unicode));
4002 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 Py_FatalError("Impossible unicode object state, wstr "
4004 "and str should share memory already.");
4005 return NULL;
4006#endif
4007 }
4008 else {
4009 assert(0 && "This should never happen.");
4010 }
4011 }
4012 }
4013 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004014 *size = PyUnicode_WSTR_LENGTH(unicode);
4015 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004016}
4017
Alexander Belopolsky40018472011-02-26 01:02:56 +00004018Py_UNICODE *
4019PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004021 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004022}
4023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024
Alexander Belopolsky40018472011-02-26 01:02:56 +00004025Py_ssize_t
4026PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004027{
4028 if (!PyUnicode_Check(unicode)) {
4029 PyErr_BadArgument();
4030 goto onError;
4031 }
4032 return PyUnicode_GET_SIZE(unicode);
4033
Benjamin Peterson29060642009-01-31 22:14:21 +00004034 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004035 return -1;
4036}
4037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038Py_ssize_t
4039PyUnicode_GetLength(PyObject *unicode)
4040{
Victor Stinner07621332012-06-16 04:53:46 +02004041 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004042 PyErr_BadArgument();
4043 return -1;
4044 }
Victor Stinner07621332012-06-16 04:53:46 +02004045 if (PyUnicode_READY(unicode) == -1)
4046 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047 return PyUnicode_GET_LENGTH(unicode);
4048}
4049
4050Py_UCS4
4051PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4052{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004053 void *data;
4054 int kind;
4055
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004056 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4057 PyErr_BadArgument();
4058 return (Py_UCS4)-1;
4059 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004060 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004061 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004062 return (Py_UCS4)-1;
4063 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004064 data = PyUnicode_DATA(unicode);
4065 kind = PyUnicode_KIND(unicode);
4066 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004067}
4068
4069int
4070PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4071{
4072 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004073 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004074 return -1;
4075 }
Victor Stinner488fa492011-12-12 00:01:39 +01004076 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004077 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004078 PyErr_SetString(PyExc_IndexError, "string index out of range");
4079 return -1;
4080 }
Victor Stinner488fa492011-12-12 00:01:39 +01004081 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004082 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004083 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4084 PyErr_SetString(PyExc_ValueError, "character out of range");
4085 return -1;
4086 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4088 index, ch);
4089 return 0;
4090}
4091
Alexander Belopolsky40018472011-02-26 01:02:56 +00004092const char *
4093PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004094{
Victor Stinner42cb4622010-09-01 19:39:01 +00004095 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004096}
4097
Victor Stinner554f3f02010-06-16 23:33:54 +00004098/* create or adjust a UnicodeDecodeError */
4099static void
4100make_decode_exception(PyObject **exceptionObject,
4101 const char *encoding,
4102 const char *input, Py_ssize_t length,
4103 Py_ssize_t startpos, Py_ssize_t endpos,
4104 const char *reason)
4105{
4106 if (*exceptionObject == NULL) {
4107 *exceptionObject = PyUnicodeDecodeError_Create(
4108 encoding, input, length, startpos, endpos, reason);
4109 }
4110 else {
4111 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4112 goto onError;
4113 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4114 goto onError;
4115 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4116 goto onError;
4117 }
4118 return;
4119
4120onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004121 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004122}
4123
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004124#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004125/* error handling callback helper:
4126 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004127 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128 and adjust various state variables.
4129 return 0 on success, -1 on error
4130*/
4131
Alexander Belopolsky40018472011-02-26 01:02:56 +00004132static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004133unicode_decode_call_errorhandler_wchar(
4134 const char *errors, PyObject **errorHandler,
4135 const char *encoding, const char *reason,
4136 const char **input, const char **inend, Py_ssize_t *startinpos,
4137 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4138 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004139{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004140 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004141
4142 PyObject *restuple = NULL;
4143 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004144 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004145 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004146 Py_ssize_t requiredsize;
4147 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004148 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004149 wchar_t *repwstr;
4150 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004151
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004152 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4153 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004154
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004155 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004156 *errorHandler = PyCodec_LookupError(errors);
4157 if (*errorHandler == NULL)
4158 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004159 }
4160
Victor Stinner554f3f02010-06-16 23:33:54 +00004161 make_decode_exception(exceptionObject,
4162 encoding,
4163 *input, *inend - *input,
4164 *startinpos, *endinpos,
4165 reason);
4166 if (*exceptionObject == NULL)
4167 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004168
4169 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4170 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004171 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004173 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004174 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 }
4176 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004177 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004178
4179 /* Copy back the bytes variables, which might have been modified by the
4180 callback */
4181 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4182 if (!inputobj)
4183 goto onError;
4184 if (!PyBytes_Check(inputobj)) {
4185 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4186 }
4187 *input = PyBytes_AS_STRING(inputobj);
4188 insize = PyBytes_GET_SIZE(inputobj);
4189 *inend = *input + insize;
4190 /* we can DECREF safely, as the exception has another reference,
4191 so the object won't go away. */
4192 Py_DECREF(inputobj);
4193
4194 if (newpos<0)
4195 newpos = insize+newpos;
4196 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004197 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004198 goto onError;
4199 }
4200
4201 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4202 if (repwstr == NULL)
4203 goto onError;
4204 /* need more space? (at least enough for what we
4205 have+the replacement+the rest of the string (starting
4206 at the new input position), so we won't have to check space
4207 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004208 requiredsize = *outpos;
4209 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4210 goto overflow;
4211 requiredsize += repwlen;
4212 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4213 goto overflow;
4214 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004215 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004216 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004217 requiredsize = 2*outsize;
4218 if (unicode_resize(output, requiredsize) < 0)
4219 goto onError;
4220 }
4221 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4222 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004223 *endinpos = newpos;
4224 *inptr = *input + newpos;
4225
4226 /* we made it! */
4227 Py_XDECREF(restuple);
4228 return 0;
4229
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004230 overflow:
4231 PyErr_SetString(PyExc_OverflowError,
4232 "decoded result is too long for a Python string");
4233
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004234 onError:
4235 Py_XDECREF(restuple);
4236 return -1;
4237}
4238#endif /* HAVE_MBCS */
4239
4240static int
4241unicode_decode_call_errorhandler_writer(
4242 const char *errors, PyObject **errorHandler,
4243 const char *encoding, const char *reason,
4244 const char **input, const char **inend, Py_ssize_t *startinpos,
4245 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4246 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4247{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004248 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004249
4250 PyObject *restuple = NULL;
4251 PyObject *repunicode = NULL;
4252 Py_ssize_t insize;
4253 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004254 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004255 PyObject *inputobj = NULL;
4256
4257 if (*errorHandler == NULL) {
4258 *errorHandler = PyCodec_LookupError(errors);
4259 if (*errorHandler == NULL)
4260 goto onError;
4261 }
4262
4263 make_decode_exception(exceptionObject,
4264 encoding,
4265 *input, *inend - *input,
4266 *startinpos, *endinpos,
4267 reason);
4268 if (*exceptionObject == NULL)
4269 goto onError;
4270
4271 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4272 if (restuple == NULL)
4273 goto onError;
4274 if (!PyTuple_Check(restuple)) {
4275 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4276 goto onError;
4277 }
4278 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004279 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004280
4281 /* Copy back the bytes variables, which might have been modified by the
4282 callback */
4283 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4284 if (!inputobj)
4285 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004286 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004287 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004288 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004289 *input = PyBytes_AS_STRING(inputobj);
4290 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004291 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004292 /* we can DECREF safely, as the exception has another reference,
4293 so the object won't go away. */
4294 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004295
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004296 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004297 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004298 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004299 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004300 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004301 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004302
Victor Stinner8f674cc2013-04-17 23:02:17 +02004303 if (PyUnicode_READY(repunicode) < 0)
4304 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004305 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004306 if (replen > 1) {
4307 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004308 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004309 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4310 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4311 goto onError;
4312 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004314 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004317 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004318
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004320 Py_XDECREF(restuple);
4321 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004322
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004324 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004326}
4327
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004328/* --- UTF-7 Codec -------------------------------------------------------- */
4329
Antoine Pitrou244651a2009-05-04 18:56:13 +00004330/* See RFC2152 for details. We encode conservatively and decode liberally. */
4331
4332/* Three simple macros defining base-64. */
4333
4334/* Is c a base-64 character? */
4335
4336#define IS_BASE64(c) \
4337 (((c) >= 'A' && (c) <= 'Z') || \
4338 ((c) >= 'a' && (c) <= 'z') || \
4339 ((c) >= '0' && (c) <= '9') || \
4340 (c) == '+' || (c) == '/')
4341
4342/* given that c is a base-64 character, what is its base-64 value? */
4343
4344#define FROM_BASE64(c) \
4345 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4346 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4347 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4348 (c) == '+' ? 62 : 63)
4349
4350/* What is the base-64 character of the bottom 6 bits of n? */
4351
4352#define TO_BASE64(n) \
4353 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4354
4355/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4356 * decoded as itself. We are permissive on decoding; the only ASCII
4357 * byte not decoding to itself is the + which begins a base64
4358 * string. */
4359
4360#define DECODE_DIRECT(c) \
4361 ((c) <= 127 && (c) != '+')
4362
4363/* The UTF-7 encoder treats ASCII characters differently according to
4364 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4365 * the above). See RFC2152. This array identifies these different
4366 * sets:
4367 * 0 : "Set D"
4368 * alphanumeric and '(),-./:?
4369 * 1 : "Set O"
4370 * !"#$%&*;<=>@[]^_`{|}
4371 * 2 : "whitespace"
4372 * ht nl cr sp
4373 * 3 : special (must be base64 encoded)
4374 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4375 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004376
Tim Petersced69f82003-09-16 20:30:58 +00004377static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378char utf7_category[128] = {
4379/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4380 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4381/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4382 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4383/* sp ! " # $ % & ' ( ) * + , - . / */
4384 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4385/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4386 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4387/* @ A B C D E F G H I J K L M N O */
4388 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4389/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4390 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4391/* ` a b c d e f g h i j k l m n o */
4392 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4393/* p q r s t u v w x y z { | } ~ del */
4394 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395};
4396
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397/* ENCODE_DIRECT: this character should be encoded as itself. The
4398 * answer depends on whether we are encoding set O as itself, and also
4399 * on whether we are encoding whitespace as itself. RFC2152 makes it
4400 * clear that the answers to these questions vary between
4401 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004402
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403#define ENCODE_DIRECT(c, directO, directWS) \
4404 ((c) < 128 && (c) > 0 && \
4405 ((utf7_category[(c)] == 0) || \
4406 (directWS && (utf7_category[(c)] == 2)) || \
4407 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408
Alexander Belopolsky40018472011-02-26 01:02:56 +00004409PyObject *
4410PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004411 Py_ssize_t size,
4412 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004414 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4415}
4416
Antoine Pitrou244651a2009-05-04 18:56:13 +00004417/* The decoder. The only state we preserve is our read position,
4418 * i.e. how many characters we have consumed. So if we end in the
4419 * middle of a shift sequence we have to back off the read position
4420 * and the output to the beginning of the sequence, otherwise we lose
4421 * all the shift state (seen bits, number of bits seen, high
4422 * surrogate). */
4423
Alexander Belopolsky40018472011-02-26 01:02:56 +00004424PyObject *
4425PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004426 Py_ssize_t size,
4427 const char *errors,
4428 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004429{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004430 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004431 Py_ssize_t startinpos;
4432 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004434 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435 const char *errmsg = "";
4436 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004437 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 unsigned int base64bits = 0;
4439 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004440 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004441 PyObject *errorHandler = NULL;
4442 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004443
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004444 if (size == 0) {
4445 if (consumed)
4446 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004447 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004448 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004449
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004450 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004451 _PyUnicodeWriter_Init(&writer);
4452 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004453
4454 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004455 e = s + size;
4456
4457 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004458 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004460 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004461
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 if (inShift) { /* in a base-64 section */
4463 if (IS_BASE64(ch)) { /* consume a base-64 character */
4464 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4465 base64bits += 6;
4466 s++;
4467 if (base64bits >= 16) {
4468 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004469 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 base64bits -= 16;
4471 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004472 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 if (surrogate) {
4474 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004475 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4476 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004477 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004478 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004480 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 }
4482 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004483 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004484 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486 }
4487 }
Victor Stinner551ac952011-11-29 22:58:13 +01004488 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489 /* first surrogate */
4490 surrogate = outCh;
4491 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004493 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004494 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 }
4496 }
4497 }
4498 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 if (base64bits > 0) { /* left-over bits */
4501 if (base64bits >= 6) {
4502 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004503 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504 errmsg = "partial character in shift sequence";
4505 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 else {
4508 /* Some bits remain; they should be zero */
4509 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004510 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004511 errmsg = "non-zero padding bits in shift sequence";
4512 goto utf7Error;
4513 }
4514 }
4515 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004516 if (surrogate && DECODE_DIRECT(ch)) {
4517 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4518 goto onError;
4519 }
4520 surrogate = 0;
4521 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 /* '-' is absorbed; other terminating
4523 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004524 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526 }
4527 }
4528 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004529 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004530 s++; /* consume '+' */
4531 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004533 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004534 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 }
4536 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004537 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004538 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004539 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004540 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004541 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
4543 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004544 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004546 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004547 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 else {
4550 startinpos = s-starts;
4551 s++;
4552 errmsg = "unexpected special character";
4553 goto utf7Error;
4554 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004557 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004559 errors, &errorHandler,
4560 "utf7", errmsg,
4561 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004562 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004563 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004564 }
4565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 /* end of string */
4567
4568 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4569 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004570 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 if (surrogate ||
4572 (base64bits >= 6) ||
4573 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004575 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 errors, &errorHandler,
4577 "utf7", "unterminated shift sequence",
4578 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004579 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 goto onError;
4581 if (s < e)
4582 goto restart;
4583 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585
4586 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004587 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004589 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004590 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004591 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004592 writer.kind, writer.data, shiftOutStart);
4593 Py_XDECREF(errorHandler);
4594 Py_XDECREF(exc);
4595 _PyUnicodeWriter_Dealloc(&writer);
4596 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004597 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004598 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 }
4600 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004601 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004603 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004605 Py_XDECREF(errorHandler);
4606 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004607 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004608
Benjamin Peterson29060642009-01-31 22:14:21 +00004609 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004610 Py_XDECREF(errorHandler);
4611 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004612 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613 return NULL;
4614}
4615
4616
Alexander Belopolsky40018472011-02-26 01:02:56 +00004617PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004618_PyUnicode_EncodeUTF7(PyObject *str,
4619 int base64SetO,
4620 int base64WhiteSpace,
4621 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004622{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004623 int kind;
4624 void *data;
4625 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004626 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004627 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004628 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629 unsigned int base64bits = 0;
4630 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004631 char * out;
4632 char * start;
4633
Benjamin Petersonbac79492012-01-14 13:34:47 -05004634 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004635 return NULL;
4636 kind = PyUnicode_KIND(str);
4637 data = PyUnicode_DATA(str);
4638 len = PyUnicode_GET_LENGTH(str);
4639
4640 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004641 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004642
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004643 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004644 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004645 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004646 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004647 if (v == NULL)
4648 return NULL;
4649
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004650 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004651 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004652 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004653
Antoine Pitrou244651a2009-05-04 18:56:13 +00004654 if (inShift) {
4655 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4656 /* shifting out */
4657 if (base64bits) { /* output remaining bits */
4658 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4659 base64buffer = 0;
4660 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004661 }
4662 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004663 /* Characters not in the BASE64 set implicitly unshift the sequence
4664 so no '-' is required, except if the character is itself a '-' */
4665 if (IS_BASE64(ch) || ch == '-') {
4666 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004667 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004668 *out++ = (char) ch;
4669 }
4670 else {
4671 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004672 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004673 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004674 else { /* not in a shift sequence */
4675 if (ch == '+') {
4676 *out++ = '+';
4677 *out++ = '-';
4678 }
4679 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4680 *out++ = (char) ch;
4681 }
4682 else {
4683 *out++ = '+';
4684 inShift = 1;
4685 goto encode_char;
4686 }
4687 }
4688 continue;
4689encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004690 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004691 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004692
Antoine Pitrou244651a2009-05-04 18:56:13 +00004693 /* code first surrogate */
4694 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004695 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004696 while (base64bits >= 6) {
4697 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4698 base64bits -= 6;
4699 }
4700 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004701 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004702 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004703 base64bits += 16;
4704 base64buffer = (base64buffer << 16) | ch;
4705 while (base64bits >= 6) {
4706 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4707 base64bits -= 6;
4708 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004709 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004710 if (base64bits)
4711 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4712 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004713 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004714 if (_PyBytes_Resize(&v, out - start) < 0)
4715 return NULL;
4716 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004717}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004718PyObject *
4719PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4720 Py_ssize_t size,
4721 int base64SetO,
4722 int base64WhiteSpace,
4723 const char *errors)
4724{
4725 PyObject *result;
4726 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4727 if (tmp == NULL)
4728 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004729 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 base64WhiteSpace, errors);
4731 Py_DECREF(tmp);
4732 return result;
4733}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734
Antoine Pitrou244651a2009-05-04 18:56:13 +00004735#undef IS_BASE64
4736#undef FROM_BASE64
4737#undef TO_BASE64
4738#undef DECODE_DIRECT
4739#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004740
Guido van Rossumd57fd912000-03-10 22:53:23 +00004741/* --- UTF-8 Codec -------------------------------------------------------- */
4742
Alexander Belopolsky40018472011-02-26 01:02:56 +00004743PyObject *
4744PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004745 Py_ssize_t size,
4746 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004747{
Walter Dörwald69652032004-09-07 20:24:22 +00004748 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4749}
4750
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004751#include "stringlib/asciilib.h"
4752#include "stringlib/codecs.h"
4753#include "stringlib/undef.h"
4754
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004755#include "stringlib/ucs1lib.h"
4756#include "stringlib/codecs.h"
4757#include "stringlib/undef.h"
4758
4759#include "stringlib/ucs2lib.h"
4760#include "stringlib/codecs.h"
4761#include "stringlib/undef.h"
4762
4763#include "stringlib/ucs4lib.h"
4764#include "stringlib/codecs.h"
4765#include "stringlib/undef.h"
4766
Antoine Pitrouab868312009-01-10 15:40:25 +00004767/* Mask to quickly check whether a C 'long' contains a
4768 non-ASCII, UTF8-encoded char. */
4769#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004770# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004771#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004772# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004773#else
4774# error C 'long' size should be either 4 or 8!
4775#endif
4776
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777static Py_ssize_t
4778ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004779{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004780 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004781 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004782
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004783 /*
4784 * Issue #17237: m68k is a bit different from most architectures in
4785 * that objects do not use "natural alignment" - for example, int and
4786 * long are only aligned at 2-byte boundaries. Therefore the assert()
4787 * won't work; also, tests have shown that skipping the "optimised
4788 * version" will even speed up m68k.
4789 */
4790#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004792 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4793 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004794 /* Fast path, see in STRINGLIB(utf8_decode) for
4795 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004796 /* Help allocation */
4797 const char *_p = p;
4798 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799 while (_p < aligned_end) {
4800 unsigned long value = *(const unsigned long *) _p;
4801 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004802 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004803 *((unsigned long *)q) = value;
4804 _p += SIZEOF_LONG;
4805 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004806 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807 p = _p;
4808 while (p < end) {
4809 if ((unsigned char)*p & 0x80)
4810 break;
4811 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004814 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004816#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004817 while (p < end) {
4818 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4819 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004820 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004821 /* Help allocation */
4822 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823 while (_p < aligned_end) {
4824 unsigned long value = *(unsigned long *) _p;
4825 if (value & ASCII_CHAR_MASK)
4826 break;
4827 _p += SIZEOF_LONG;
4828 }
4829 p = _p;
4830 if (_p == end)
4831 break;
4832 }
4833 if ((unsigned char)*p & 0x80)
4834 break;
4835 ++p;
4836 }
4837 memcpy(dest, start, p - start);
4838 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004839}
Antoine Pitrouab868312009-01-10 15:40:25 +00004840
Victor Stinner785938e2011-12-11 20:09:03 +01004841PyObject *
4842PyUnicode_DecodeUTF8Stateful(const char *s,
4843 Py_ssize_t size,
4844 const char *errors,
4845 Py_ssize_t *consumed)
4846{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004847 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004848 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850
4851 Py_ssize_t startinpos;
4852 Py_ssize_t endinpos;
4853 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004854 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004855 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004856 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004857
4858 if (size == 0) {
4859 if (consumed)
4860 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004861 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004862 }
4863
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4865 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004866 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 *consumed = 1;
4868 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004869 }
4870
Victor Stinner8f674cc2013-04-17 23:02:17 +02004871 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004872 writer.min_length = size;
4873 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004874 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004875
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004876 writer.pos = ascii_decode(s, end, writer.data);
4877 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004878 while (s < end) {
4879 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004880 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004881
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004882 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004883 if (PyUnicode_IS_ASCII(writer.buffer))
4884 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004885 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004886 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004888 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004889 } else {
4890 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004891 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004892 }
4893
4894 switch (ch) {
4895 case 0:
4896 if (s == end || consumed)
4897 goto End;
4898 errmsg = "unexpected end of data";
4899 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004900 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 break;
4902 case 1:
4903 errmsg = "invalid start byte";
4904 startinpos = s - starts;
4905 endinpos = startinpos + 1;
4906 break;
4907 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004908 case 3:
4909 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910 errmsg = "invalid continuation byte";
4911 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004912 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004913 break;
4914 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004915 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004916 goto onError;
4917 continue;
4918 }
4919
Victor Stinner1d65d912015-10-05 13:43:50 +02004920 if (error_handler == _Py_ERROR_UNKNOWN)
4921 error_handler = get_error_handler(errors);
4922
4923 switch (error_handler) {
4924 case _Py_ERROR_IGNORE:
4925 s += (endinpos - startinpos);
4926 break;
4927
4928 case _Py_ERROR_REPLACE:
4929 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4930 goto onError;
4931 s += (endinpos - startinpos);
4932 break;
4933
4934 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004935 {
4936 Py_ssize_t i;
4937
Victor Stinner1d65d912015-10-05 13:43:50 +02004938 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4939 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004940 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004941 ch = (Py_UCS4)(unsigned char)(starts[i]);
4942 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4943 ch + 0xdc00);
4944 writer.pos++;
4945 }
4946 s += (endinpos - startinpos);
4947 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004948 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004949
4950 default:
4951 if (unicode_decode_call_errorhandler_writer(
4952 errors, &error_handler_obj,
4953 "utf-8", errmsg,
4954 &starts, &end, &startinpos, &endinpos, &exc, &s,
4955 &writer))
4956 goto onError;
4957 }
Victor Stinner785938e2011-12-11 20:09:03 +01004958 }
4959
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004961 if (consumed)
4962 *consumed = s - starts;
4963
Victor Stinner1d65d912015-10-05 13:43:50 +02004964 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004966 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004967
4968onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004969 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004971 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004973}
4974
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004975#ifdef __APPLE__
4976
4977/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004978 used to decode the command line arguments on Mac OS X.
4979
4980 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004981 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004982
4983wchar_t*
4984_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4985{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004986 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 wchar_t *unicode;
4988 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004989
4990 /* Note: size will always be longer than the resulting Unicode
4991 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004992 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004993 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004994 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004995 if (!unicode)
4996 return NULL;
4997
4998 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004999 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005000 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005001 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005003#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005005#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005007#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 if (ch > 0xFF) {
5009#if SIZEOF_WCHAR_T == 4
5010 assert(0);
5011#else
5012 assert(Py_UNICODE_IS_SURROGATE(ch));
5013 /* compute and append the two surrogates: */
5014 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5015 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5016#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005017 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005018 else {
5019 if (!ch && s == e)
5020 break;
5021 /* surrogateescape */
5022 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5023 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005024 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005025 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005026 return unicode;
5027}
5028
5029#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005031/* Primary internal function which creates utf8 encoded bytes objects.
5032
5033 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005034 and allocate exactly as much space needed at the end. Else allocate the
5035 maximum possible needed (4 result bytes per Unicode character), and return
5036 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005037*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005038PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005039_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005040{
Victor Stinner6099a032011-12-18 14:22:26 +01005041 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005042 void *data;
5043 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005045 if (!PyUnicode_Check(unicode)) {
5046 PyErr_BadArgument();
5047 return NULL;
5048 }
5049
5050 if (PyUnicode_READY(unicode) == -1)
5051 return NULL;
5052
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005053 if (PyUnicode_UTF8(unicode))
5054 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5055 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056
5057 kind = PyUnicode_KIND(unicode);
5058 data = PyUnicode_DATA(unicode);
5059 size = PyUnicode_GET_LENGTH(unicode);
5060
Benjamin Petersonead6b532011-12-20 17:23:42 -06005061 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005062 default:
5063 assert(0);
5064 case PyUnicode_1BYTE_KIND:
5065 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5066 assert(!PyUnicode_IS_ASCII(unicode));
5067 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5068 case PyUnicode_2BYTE_KIND:
5069 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5070 case PyUnicode_4BYTE_KIND:
5071 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005072 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005073}
5074
Alexander Belopolsky40018472011-02-26 01:02:56 +00005075PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005076PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5077 Py_ssize_t size,
5078 const char *errors)
5079{
5080 PyObject *v, *unicode;
5081
5082 unicode = PyUnicode_FromUnicode(s, size);
5083 if (unicode == NULL)
5084 return NULL;
5085 v = _PyUnicode_AsUTF8String(unicode, errors);
5086 Py_DECREF(unicode);
5087 return v;
5088}
5089
5090PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005091PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005093 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005094}
5095
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096/* --- UTF-32 Codec ------------------------------------------------------- */
5097
5098PyObject *
5099PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005100 Py_ssize_t size,
5101 const char *errors,
5102 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103{
5104 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5105}
5106
5107PyObject *
5108PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005109 Py_ssize_t size,
5110 const char *errors,
5111 int *byteorder,
5112 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113{
5114 const char *starts = s;
5115 Py_ssize_t startinpos;
5116 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005117 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005118 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005119 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005120 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122 PyObject *errorHandler = NULL;
5123 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005124
Walter Dörwald41980ca2007-08-16 21:55:45 +00005125 q = (unsigned char *)s;
5126 e = q + size;
5127
5128 if (byteorder)
5129 bo = *byteorder;
5130
5131 /* Check for BOM marks (U+FEFF) in the input and adjust current
5132 byte order setting accordingly. In native mode, the leading BOM
5133 mark is skipped, in all other modes, it is copied to the output
5134 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005135 if (bo == 0 && size >= 4) {
5136 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5137 if (bom == 0x0000FEFF) {
5138 bo = -1;
5139 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005140 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005141 else if (bom == 0xFFFE0000) {
5142 bo = 1;
5143 q += 4;
5144 }
5145 if (byteorder)
5146 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 }
5148
Victor Stinnere64322e2012-10-30 23:12:47 +01005149 if (q == e) {
5150 if (consumed)
5151 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005152 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153 }
5154
Victor Stinnere64322e2012-10-30 23:12:47 +01005155#ifdef WORDS_BIGENDIAN
5156 le = bo < 0;
5157#else
5158 le = bo <= 0;
5159#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005160 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005161
Victor Stinner8f674cc2013-04-17 23:02:17 +02005162 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005163 writer.min_length = (e - q + 3) / 4;
5164 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005165 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005166
Victor Stinnere64322e2012-10-30 23:12:47 +01005167 while (1) {
5168 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005169 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005170
Victor Stinnere64322e2012-10-30 23:12:47 +01005171 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005172 enum PyUnicode_Kind kind = writer.kind;
5173 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005174 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005175 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005176 if (le) {
5177 do {
5178 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5179 if (ch > maxch)
5180 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005181 if (kind != PyUnicode_1BYTE_KIND &&
5182 Py_UNICODE_IS_SURROGATE(ch))
5183 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005184 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005185 q += 4;
5186 } while (q <= last);
5187 }
5188 else {
5189 do {
5190 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5191 if (ch > maxch)
5192 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 if (kind != PyUnicode_1BYTE_KIND &&
5194 Py_UNICODE_IS_SURROGATE(ch))
5195 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005196 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005197 q += 4;
5198 } while (q <= last);
5199 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005200 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005201 }
5202
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005203 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005204 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005205 startinpos = ((const char *)q) - starts;
5206 endinpos = startinpos + 4;
5207 }
5208 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005209 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005211 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005212 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005213 startinpos = ((const char *)q) - starts;
5214 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005215 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005216 else {
5217 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005218 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005219 goto onError;
5220 q += 4;
5221 continue;
5222 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005223 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005224 startinpos = ((const char *)q) - starts;
5225 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005226 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005227
5228 /* The remaining input chars are ignored if the callback
5229 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005230 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005232 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005233 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005234 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005236 }
5237
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005240
Walter Dörwald41980ca2007-08-16 21:55:45 +00005241 Py_XDECREF(errorHandler);
5242 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005243 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005244
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005246 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005247 Py_XDECREF(errorHandler);
5248 Py_XDECREF(exc);
5249 return NULL;
5250}
5251
5252PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005253_PyUnicode_EncodeUTF32(PyObject *str,
5254 const char *errors,
5255 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005257 enum PyUnicode_Kind kind;
5258 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005259 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005260 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005261 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005262#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005263 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005265 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005267 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005268 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005269 PyObject *errorHandler = NULL;
5270 PyObject *exc = NULL;
5271 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005272
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005273 if (!PyUnicode_Check(str)) {
5274 PyErr_BadArgument();
5275 return NULL;
5276 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005277 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005278 return NULL;
5279 kind = PyUnicode_KIND(str);
5280 data = PyUnicode_DATA(str);
5281 len = PyUnicode_GET_LENGTH(str);
5282
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005283 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005284 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005285 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005286 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005287 if (v == NULL)
5288 return NULL;
5289
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005290 /* output buffer is 4-bytes aligned */
5291 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5292 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005293 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005294 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005295 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005296 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005297
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005298 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005299 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005300 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005301 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005302 else
5303 encoding = "utf-32";
5304
5305 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005306 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5307 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005308 }
5309
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005310 pos = 0;
5311 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005312 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005313
5314 if (kind == PyUnicode_2BYTE_KIND) {
5315 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5316 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005317 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005318 else {
5319 assert(kind == PyUnicode_4BYTE_KIND);
5320 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5321 &out, native_ordering);
5322 }
5323 if (pos == len)
5324 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005325
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005326 rep = unicode_encode_call_errorhandler(
5327 errors, &errorHandler,
5328 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005329 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005330 if (!rep)
5331 goto error;
5332
5333 if (PyBytes_Check(rep)) {
5334 repsize = PyBytes_GET_SIZE(rep);
5335 if (repsize & 3) {
5336 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005337 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005338 "surrogates not allowed");
5339 goto error;
5340 }
5341 moreunits = repsize / 4;
5342 }
5343 else {
5344 assert(PyUnicode_Check(rep));
5345 if (PyUnicode_READY(rep) < 0)
5346 goto error;
5347 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5348 if (!PyUnicode_IS_ASCII(rep)) {
5349 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005350 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005351 "surrogates not allowed");
5352 goto error;
5353 }
5354 }
5355
5356 /* four bytes are reserved for each surrogate */
5357 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005358 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005359 Py_ssize_t morebytes = 4 * (moreunits - 1);
5360 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5361 /* integer overflow */
5362 PyErr_NoMemory();
5363 goto error;
5364 }
5365 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5366 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 }
5369
5370 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005371 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5372 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005373 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005374 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005375 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5376 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005377 }
5378
5379 Py_CLEAR(rep);
5380 }
5381
5382 /* Cut back to size actually needed. This is necessary for, for example,
5383 encoding of a string containing isolated surrogates and the 'ignore'
5384 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005385 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005386 if (nsize != PyBytes_GET_SIZE(v))
5387 _PyBytes_Resize(&v, nsize);
5388 Py_XDECREF(errorHandler);
5389 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005391 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005392 error:
5393 Py_XDECREF(rep);
5394 Py_XDECREF(errorHandler);
5395 Py_XDECREF(exc);
5396 Py_XDECREF(v);
5397 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398}
5399
Alexander Belopolsky40018472011-02-26 01:02:56 +00005400PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005401PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5402 Py_ssize_t size,
5403 const char *errors,
5404 int byteorder)
5405{
5406 PyObject *result;
5407 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5408 if (tmp == NULL)
5409 return NULL;
5410 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5411 Py_DECREF(tmp);
5412 return result;
5413}
5414
5415PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005416PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005417{
Victor Stinnerb960b342011-11-20 19:12:52 +01005418 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005419}
5420
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421/* --- UTF-16 Codec ------------------------------------------------------- */
5422
Tim Peters772747b2001-08-09 22:21:55 +00005423PyObject *
5424PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005425 Py_ssize_t size,
5426 const char *errors,
5427 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428{
Walter Dörwald69652032004-09-07 20:24:22 +00005429 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5430}
5431
5432PyObject *
5433PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 Py_ssize_t size,
5435 const char *errors,
5436 int *byteorder,
5437 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005438{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005439 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005440 Py_ssize_t startinpos;
5441 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005442 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005443 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005444 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005445 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005446 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005447 PyObject *errorHandler = NULL;
5448 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005449 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005450
Tim Peters772747b2001-08-09 22:21:55 +00005451 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005452 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453
5454 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005455 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005457 /* Check for BOM marks (U+FEFF) in the input and adjust current
5458 byte order setting accordingly. In native mode, the leading BOM
5459 mark is skipped, in all other modes, it is copied to the output
5460 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005461 if (bo == 0 && size >= 2) {
5462 const Py_UCS4 bom = (q[1] << 8) | q[0];
5463 if (bom == 0xFEFF) {
5464 q += 2;
5465 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005466 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005467 else if (bom == 0xFFFE) {
5468 q += 2;
5469 bo = 1;
5470 }
5471 if (byteorder)
5472 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005473 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005474
Antoine Pitrou63065d72012-05-15 23:48:04 +02005475 if (q == e) {
5476 if (consumed)
5477 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005478 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005479 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005480
Christian Heimes743e0cd2012-10-17 23:52:17 +02005481#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005482 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005483 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005484#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005485 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005486 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005487#endif
Tim Peters772747b2001-08-09 22:21:55 +00005488
Antoine Pitrou63065d72012-05-15 23:48:04 +02005489 /* Note: size will always be longer than the resulting Unicode
5490 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005491 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005492 writer.min_length = (e - q + 1) / 2;
5493 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005494 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005495
Antoine Pitrou63065d72012-05-15 23:48:04 +02005496 while (1) {
5497 Py_UCS4 ch = 0;
5498 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005499 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005500 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005501 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005502 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005503 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005504 native_ordering);
5505 else
5506 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005507 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005508 native_ordering);
5509 } else if (kind == PyUnicode_2BYTE_KIND) {
5510 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005511 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005512 native_ordering);
5513 } else {
5514 assert(kind == PyUnicode_4BYTE_KIND);
5515 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005516 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005517 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005518 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005519 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005520
Antoine Pitrou63065d72012-05-15 23:48:04 +02005521 switch (ch)
5522 {
5523 case 0:
5524 /* remaining byte at the end? (size should be even) */
5525 if (q == e || consumed)
5526 goto End;
5527 errmsg = "truncated data";
5528 startinpos = ((const char *)q) - starts;
5529 endinpos = ((const char *)e) - starts;
5530 break;
5531 /* The remaining input chars are ignored if the callback
5532 chooses to skip the input */
5533 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005534 q -= 2;
5535 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005536 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005537 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005538 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005539 endinpos = ((const char *)e) - starts;
5540 break;
5541 case 2:
5542 errmsg = "illegal encoding";
5543 startinpos = ((const char *)q) - 2 - starts;
5544 endinpos = startinpos + 2;
5545 break;
5546 case 3:
5547 errmsg = "illegal UTF-16 surrogate";
5548 startinpos = ((const char *)q) - 4 - starts;
5549 endinpos = startinpos + 2;
5550 break;
5551 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005552 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005553 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005554 continue;
5555 }
5556
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005557 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005558 errors,
5559 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005560 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005561 &starts,
5562 (const char **)&e,
5563 &startinpos,
5564 &endinpos,
5565 &exc,
5566 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005567 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005568 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569 }
5570
Antoine Pitrou63065d72012-05-15 23:48:04 +02005571End:
Walter Dörwald69652032004-09-07 20:24:22 +00005572 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005573 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005574
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005575 Py_XDECREF(errorHandler);
5576 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005577 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005580 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005581 Py_XDECREF(errorHandler);
5582 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583 return NULL;
5584}
5585
Tim Peters772747b2001-08-09 22:21:55 +00005586PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005587_PyUnicode_EncodeUTF16(PyObject *str,
5588 const char *errors,
5589 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005591 enum PyUnicode_Kind kind;
5592 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005593 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005594 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005595 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005596 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005597#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005598 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005599#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005600 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005601#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005602 const char *encoding;
5603 Py_ssize_t nsize, pos;
5604 PyObject *errorHandler = NULL;
5605 PyObject *exc = NULL;
5606 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005607
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005608 if (!PyUnicode_Check(str)) {
5609 PyErr_BadArgument();
5610 return NULL;
5611 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005612 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005613 return NULL;
5614 kind = PyUnicode_KIND(str);
5615 data = PyUnicode_DATA(str);
5616 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005617
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005618 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005619 if (kind == PyUnicode_4BYTE_KIND) {
5620 const Py_UCS4 *in = (const Py_UCS4 *)data;
5621 const Py_UCS4 *end = in + len;
5622 while (in < end)
5623 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005624 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005625 }
5626 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005628 nsize = len + pairs + (byteorder == 0);
5629 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 if (v == NULL)
5631 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005633 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005634 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005635 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005637 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005638 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005639 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005640
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005641 if (kind == PyUnicode_1BYTE_KIND) {
5642 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5643 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005644 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005645
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005646 if (byteorder < 0)
5647 encoding = "utf-16-le";
5648 else if (byteorder > 0)
5649 encoding = "utf-16-be";
5650 else
5651 encoding = "utf-16";
5652
5653 pos = 0;
5654 while (pos < len) {
5655 Py_ssize_t repsize, moreunits;
5656
5657 if (kind == PyUnicode_2BYTE_KIND) {
5658 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5659 &out, native_ordering);
5660 }
5661 else {
5662 assert(kind == PyUnicode_4BYTE_KIND);
5663 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5664 &out, native_ordering);
5665 }
5666 if (pos == len)
5667 break;
5668
5669 rep = unicode_encode_call_errorhandler(
5670 errors, &errorHandler,
5671 encoding, "surrogates not allowed",
5672 str, &exc, pos, pos + 1, &pos);
5673 if (!rep)
5674 goto error;
5675
5676 if (PyBytes_Check(rep)) {
5677 repsize = PyBytes_GET_SIZE(rep);
5678 if (repsize & 1) {
5679 raise_encode_exception(&exc, encoding,
5680 str, pos - 1, pos,
5681 "surrogates not allowed");
5682 goto error;
5683 }
5684 moreunits = repsize / 2;
5685 }
5686 else {
5687 assert(PyUnicode_Check(rep));
5688 if (PyUnicode_READY(rep) < 0)
5689 goto error;
5690 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5691 if (!PyUnicode_IS_ASCII(rep)) {
5692 raise_encode_exception(&exc, encoding,
5693 str, pos - 1, pos,
5694 "surrogates not allowed");
5695 goto error;
5696 }
5697 }
5698
5699 /* two bytes are reserved for each surrogate */
5700 if (moreunits > 1) {
5701 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5702 Py_ssize_t morebytes = 2 * (moreunits - 1);
5703 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5704 /* integer overflow */
5705 PyErr_NoMemory();
5706 goto error;
5707 }
5708 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5709 goto error;
5710 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5711 }
5712
5713 if (PyBytes_Check(rep)) {
5714 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5715 out += moreunits;
5716 } else /* rep is unicode */ {
5717 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5718 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5719 &out, native_ordering);
5720 }
5721
5722 Py_CLEAR(rep);
5723 }
5724
5725 /* Cut back to size actually needed. This is necessary for, for example,
5726 encoding of a string containing isolated surrogates and the 'ignore' handler
5727 is used. */
5728 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5729 if (nsize != PyBytes_GET_SIZE(v))
5730 _PyBytes_Resize(&v, nsize);
5731 Py_XDECREF(errorHandler);
5732 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005733 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005734 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005735 error:
5736 Py_XDECREF(rep);
5737 Py_XDECREF(errorHandler);
5738 Py_XDECREF(exc);
5739 Py_XDECREF(v);
5740 return NULL;
5741#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742}
5743
Alexander Belopolsky40018472011-02-26 01:02:56 +00005744PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005745PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5746 Py_ssize_t size,
5747 const char *errors,
5748 int byteorder)
5749{
5750 PyObject *result;
5751 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5752 if (tmp == NULL)
5753 return NULL;
5754 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5755 Py_DECREF(tmp);
5756 return result;
5757}
5758
5759PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005760PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005762 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763}
5764
5765/* --- Unicode Escape Codec ----------------------------------------------- */
5766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5768 if all the escapes in the string make it still a valid ASCII string.
5769 Returns -1 if any escapes were found which cause the string to
5770 pop out of ASCII range. Otherwise returns the length of the
5771 required buffer to hold the string.
5772 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005773static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005774length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5775{
5776 const unsigned char *p = (const unsigned char *)s;
5777 const unsigned char *end = p + size;
5778 Py_ssize_t length = 0;
5779
5780 if (size < 0)
5781 return -1;
5782
5783 for (; p < end; ++p) {
5784 if (*p > 127) {
5785 /* Non-ASCII */
5786 return -1;
5787 }
5788 else if (*p != '\\') {
5789 /* Normal character */
5790 ++length;
5791 }
5792 else {
5793 /* Backslash-escape, check next char */
5794 ++p;
5795 /* Escape sequence reaches till end of string or
5796 non-ASCII follow-up. */
5797 if (p >= end || *p > 127)
5798 return -1;
5799 switch (*p) {
5800 case '\n':
5801 /* backslash + \n result in zero characters */
5802 break;
5803 case '\\': case '\'': case '\"':
5804 case 'b': case 'f': case 't':
5805 case 'n': case 'r': case 'v': case 'a':
5806 ++length;
5807 break;
5808 case '0': case '1': case '2': case '3':
5809 case '4': case '5': case '6': case '7':
5810 case 'x': case 'u': case 'U': case 'N':
5811 /* these do not guarantee ASCII characters */
5812 return -1;
5813 default:
5814 /* count the backslash + the other character */
5815 length += 2;
5816 }
5817 }
5818 }
5819 return length;
5820}
5821
Fredrik Lundh06d12682001-01-24 07:59:11 +00005822static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005823
Alexander Belopolsky40018472011-02-26 01:02:56 +00005824PyObject *
5825PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005826 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005827 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005828{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005830 Py_ssize_t startinpos;
5831 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005832 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005833 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 char* message;
5835 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005836 PyObject *errorHandler = NULL;
5837 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005838 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005839
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005840 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005841 if (len == 0)
5842 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843
5844 /* After length_of_escaped_ascii_string() there are two alternatives,
5845 either the string is pure ASCII with named escapes like \n, etc.
5846 and we determined it's exact size (common case)
5847 or it contains \x, \u, ... escape sequences. then we create a
5848 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005849 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005850 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005851 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 }
5853 else {
5854 /* Escaped strings will always be longer than the resulting
5855 Unicode string, so we start with size here and then reduce the
5856 length after conversion to the true value.
5857 (but if the error callback returns a long replacement string
5858 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005859 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005860 }
5861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005863 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005865
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 while (s < end) {
5867 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005868 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870
5871 /* Non-escape characters are interpreted as Unicode ordinals */
5872 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005873 x = (unsigned char)*s;
5874 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005875 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 continue;
5878 }
5879
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005880 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 /* \ - Escapes */
5882 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005883 c = *s++;
5884 if (s > end)
5885 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005887 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005890#define WRITECHAR(ch) \
5891 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005892 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005893 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005894 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005895
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005897 case '\\': WRITECHAR('\\'); break;
5898 case '\'': WRITECHAR('\''); break;
5899 case '\"': WRITECHAR('\"'); break;
5900 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005902 case 'f': WRITECHAR('\014'); break;
5903 case 't': WRITECHAR('\t'); break;
5904 case 'n': WRITECHAR('\n'); break;
5905 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005906 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005907 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005908 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005909 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 case '0': case '1': case '2': case '3':
5913 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005914 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005915 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005916 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005917 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005918 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005920 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921 break;
5922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* hex escapes */
5924 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005926 digits = 2;
5927 message = "truncated \\xXX escape";
5928 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005932 digits = 4;
5933 message = "truncated \\uXXXX escape";
5934 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005937 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005938 digits = 8;
5939 message = "truncated \\UXXXXXXXX escape";
5940 hexescape:
5941 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005942 if (end - s < digits) {
5943 /* count only hex digits */
5944 for (; s < end; ++s) {
5945 c = (unsigned char)*s;
5946 if (!Py_ISXDIGIT(c))
5947 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005948 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005949 goto error;
5950 }
5951 for (; digits--; ++s) {
5952 c = (unsigned char)*s;
5953 if (!Py_ISXDIGIT(c))
5954 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005955 chr = (chr<<4) & ~0xF;
5956 if (c >= '0' && c <= '9')
5957 chr += c - '0';
5958 else if (c >= 'a' && c <= 'f')
5959 chr += 10 + c - 'a';
5960 else
5961 chr += 10 + c - 'A';
5962 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005963 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005964 /* _decoding_error will have already written into the
5965 target buffer. */
5966 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005967 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005968 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005969 message = "illegal Unicode character";
5970 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005971 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005972 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005973 break;
5974
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005976 case 'N':
5977 message = "malformed \\N character escape";
5978 if (ucnhash_CAPI == NULL) {
5979 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005980 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5981 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005982 if (ucnhash_CAPI == NULL)
5983 goto ucnhashError;
5984 }
5985 if (*s == '{') {
5986 const char *start = s+1;
5987 /* look for the closing brace */
5988 while (*s != '}' && s < end)
5989 s++;
5990 if (s > start && s < end && *s == '}') {
5991 /* found a name. look it up in the unicode database */
5992 message = "unknown Unicode character name";
5993 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005994 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005995 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005996 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005997 goto store;
5998 }
5999 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006000 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001
6002 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006003 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006004 message = "\\ at end of string";
6005 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02006006 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00006007 }
6008 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006009 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02006010 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006011 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006012 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006014 continue;
6015
6016 error:
6017 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006018 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006019 errors, &errorHandler,
6020 "unicodeescape", message,
6021 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006022 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02006023 goto onError;
6024 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006026#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006027
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006028 Py_XDECREF(errorHandler);
6029 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006030 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006031
Benjamin Peterson29060642009-01-31 22:14:21 +00006032 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006033 PyErr_SetString(
6034 PyExc_UnicodeError,
6035 "\\N escapes not supported (can't load unicodedata module)"
6036 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006037 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 Py_XDECREF(errorHandler);
6039 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006040 return NULL;
6041
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006043 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006044 Py_XDECREF(errorHandler);
6045 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046 return NULL;
6047}
6048
6049/* Return a Unicode-Escape string version of the Unicode object.
6050
6051 If quotes is true, the string is enclosed in u"" or u'' quotes as
6052 appropriate.
6053
6054*/
6055
Alexander Belopolsky40018472011-02-26 01:02:56 +00006056PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006057PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006059 Py_ssize_t i, len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006061 int kind;
6062 void *data;
Victor Stinner358af132015-10-12 22:36:57 +02006063 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064
Ezio Melottie7f90372012-10-05 03:33:31 +03006065 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006066 escape.
6067
Ezio Melottie7f90372012-10-05 03:33:31 +03006068 For UCS1 strings it's '\xxx', 4 bytes per source character.
6069 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6070 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006071 */
6072
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073 if (!PyUnicode_Check(unicode)) {
6074 PyErr_BadArgument();
6075 return NULL;
6076 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006077 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006079
6080 _PyBytesWriter_Init(&writer);
6081
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006082 len = PyUnicode_GET_LENGTH(unicode);
6083 kind = PyUnicode_KIND(unicode);
6084 data = PyUnicode_DATA(unicode);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006085
Victor Stinner358af132015-10-12 22:36:57 +02006086 p = _PyBytesWriter_Alloc(&writer, len);
6087 if (p == NULL)
6088 goto error;
6089 writer.overallocate = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006091 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006092 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006093
Walter Dörwald79e913e2007-05-12 11:08:06 +00006094 /* Escape backslashes */
6095 if (ch == '\\') {
Victor Stinner358af132015-10-12 22:36:57 +02006096 /* -1: substract 1 preallocated byte */
6097 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6098 if (p == NULL)
6099 goto error;
6100
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101 *p++ = '\\';
6102 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006103 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006104 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006105
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006106 /* Map 21-bit characters to '\U00xxxxxx' */
6107 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006108 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006109
6110 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6111 if (p == NULL)
6112 goto error;
6113
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006114 *p++ = '\\';
6115 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006116 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6117 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6118 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6119 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6120 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6121 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6122 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6123 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006125 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006126
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006128 if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006129 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6130 if (p == NULL)
6131 goto error;
6132
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133 *p++ = '\\';
6134 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006135 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6136 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6137 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6138 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006140
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006141 /* Map special whitespace to '\t', \n', '\r' */
6142 else if (ch == '\t') {
Victor Stinner358af132015-10-12 22:36:57 +02006143 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6144 if (p == NULL)
6145 goto error;
6146
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006147 *p++ = '\\';
6148 *p++ = 't';
6149 }
6150 else if (ch == '\n') {
Victor Stinner358af132015-10-12 22:36:57 +02006151 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6152 if (p == NULL)
6153 goto error;
6154
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006155 *p++ = '\\';
6156 *p++ = 'n';
6157 }
6158 else if (ch == '\r') {
Victor Stinner358af132015-10-12 22:36:57 +02006159 p = _PyBytesWriter_Prepare(&writer, p, 2-1);
6160 if (p == NULL)
6161 goto error;
6162
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006163 *p++ = '\\';
6164 *p++ = 'r';
6165 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006166
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006167 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006168 else if (ch < ' ' || ch >= 0x7F) {
Victor Stinner358af132015-10-12 22:36:57 +02006169 /* -1: substract 1 preallocated byte */
6170 p = _PyBytesWriter_Prepare(&writer, p, 4-1);
6171 if (p == NULL)
6172 goto error;
6173
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006175 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006176 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6177 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006178 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006179
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180 /* Copy everything else as-is */
6181 else
6182 *p++ = (char) ch;
6183 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184
Victor Stinner358af132015-10-12 22:36:57 +02006185 return _PyBytesWriter_Finish(&writer, p);
6186
6187error:
6188 _PyBytesWriter_Dealloc(&writer);
6189 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006190}
6191
Alexander Belopolsky40018472011-02-26 01:02:56 +00006192PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6194 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006196 PyObject *result;
6197 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6198 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 result = PyUnicode_AsUnicodeEscapeString(tmp);
6201 Py_DECREF(tmp);
6202 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203}
6204
6205/* --- Raw Unicode Escape Codec ------------------------------------------- */
6206
Alexander Belopolsky40018472011-02-26 01:02:56 +00006207PyObject *
6208PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006209 Py_ssize_t size,
6210 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006212 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006213 Py_ssize_t startinpos;
6214 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006215 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 const char *end;
6217 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006218 PyObject *errorHandler = NULL;
6219 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006220
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006221 if (size == 0)
6222 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006223
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224 /* Escaped strings will always be longer than the resulting
6225 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006226 length after conversion to the true value. (But decoding error
6227 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006228 _PyUnicodeWriter_Init(&writer);
6229 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006230
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231 end = s + size;
6232 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006233 unsigned char c;
6234 Py_UCS4 x;
6235 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006236 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237
Benjamin Peterson29060642009-01-31 22:14:21 +00006238 /* Non-escape characters are interpreted as Unicode ordinals */
6239 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006240 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006241 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006242 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006243 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006244 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 startinpos = s-starts;
6246
6247 /* \u-escapes are only interpreted iff the number of leading
6248 backslashes if odd */
6249 bs = s;
6250 for (;s < end;) {
6251 if (*s != '\\')
6252 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006253 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006254 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006255 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 }
6257 if (((s - bs) & 1) == 0 ||
6258 s >= end ||
6259 (*s != 'u' && *s != 'U')) {
6260 continue;
6261 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006262 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 count = *s=='u' ? 4 : 8;
6264 s++;
6265
6266 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 for (x = 0, i = 0; i < count; ++i, ++s) {
6268 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006269 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006271 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 errors, &errorHandler,
6273 "rawunicodeescape", "truncated \\uXXXX",
6274 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006275 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 goto onError;
6277 goto nextByte;
6278 }
6279 x = (x<<4) & ~0xF;
6280 if (c >= '0' && c <= '9')
6281 x += c - '0';
6282 else if (c >= 'a' && c <= 'f')
6283 x += 10 + c - 'a';
6284 else
6285 x += 10 + c - 'A';
6286 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006287 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006288 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006289 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006290 }
6291 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006292 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006293 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006294 errors, &errorHandler,
6295 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006297 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 nextByte:
6301 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006303 Py_XDECREF(errorHandler);
6304 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006305 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006306
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006308 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006309 Py_XDECREF(errorHandler);
6310 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 return NULL;
6312}
6313
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006314
Alexander Belopolsky40018472011-02-26 01:02:56 +00006315PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006316PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006318 char *p;
Victor Stinner358af132015-10-12 22:36:57 +02006319 Py_ssize_t pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006320 int kind;
6321 void *data;
6322 Py_ssize_t len;
Victor Stinner358af132015-10-12 22:36:57 +02006323 _PyBytesWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006325 if (!PyUnicode_Check(unicode)) {
6326 PyErr_BadArgument();
6327 return NULL;
6328 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006329 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006330 return NULL;
Victor Stinner358af132015-10-12 22:36:57 +02006331
6332 _PyBytesWriter_Init(&writer);
6333
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006334 kind = PyUnicode_KIND(unicode);
6335 data = PyUnicode_DATA(unicode);
6336 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner0e368262011-11-10 20:12:49 +01006337
Victor Stinner358af132015-10-12 22:36:57 +02006338 p = _PyBytesWriter_Alloc(&writer, len);
6339 if (p == NULL)
6340 goto error;
6341 writer.overallocate = 1;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006342
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006343 for (pos = 0; pos < len; pos++) {
6344 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006345 /* Map 32-bit characters to '\Uxxxxxxxx' */
6346 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006347 assert(ch <= MAX_UNICODE);
Victor Stinner358af132015-10-12 22:36:57 +02006348
6349 /* -1: substract 1 preallocated byte */
6350 p = _PyBytesWriter_Prepare(&writer, p, 10-1);
6351 if (p == NULL)
6352 goto error;
6353
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006354 *p++ = '\\';
6355 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006356 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6357 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6358 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6359 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6360 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6361 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6362 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6363 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006364 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006366 else if (ch >= 256) {
Victor Stinner358af132015-10-12 22:36:57 +02006367 /* -1: substract 1 preallocated byte */
6368 p = _PyBytesWriter_Prepare(&writer, p, 6-1);
6369 if (p == NULL)
6370 goto error;
6371
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 *p++ = '\\';
6373 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006374 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6375 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6376 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6377 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 /* Copy everything else as-is */
6380 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006381 *p++ = (char) ch;
6382 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006383
Victor Stinner358af132015-10-12 22:36:57 +02006384 return _PyBytesWriter_Finish(&writer, p);
6385
6386error:
6387 _PyBytesWriter_Dealloc(&writer);
6388 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389}
6390
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6393 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006395 PyObject *result;
6396 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6397 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006398 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006399 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6400 Py_DECREF(tmp);
6401 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006402}
6403
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006404/* --- Unicode Internal Codec ------------------------------------------- */
6405
Alexander Belopolsky40018472011-02-26 01:02:56 +00006406PyObject *
6407_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006408 Py_ssize_t size,
6409 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006410{
6411 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006412 Py_ssize_t startinpos;
6413 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006414 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006415 const char *end;
6416 const char *reason;
6417 PyObject *errorHandler = NULL;
6418 PyObject *exc = NULL;
6419
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006420 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006421 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006422 1))
6423 return NULL;
6424
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006425 if (size == 0)
6426 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006427
Victor Stinner8f674cc2013-04-17 23:02:17 +02006428 _PyUnicodeWriter_Init(&writer);
6429 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6430 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006432 }
6433 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006434
Victor Stinner8f674cc2013-04-17 23:02:17 +02006435 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006436 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006437 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006438 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006439 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006440 endinpos = end-starts;
6441 reason = "truncated input";
6442 goto error;
6443 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006444 /* We copy the raw representation one byte at a time because the
6445 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006446 ((char *) &uch)[0] = s[0];
6447 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006448#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006449 ((char *) &uch)[2] = s[2];
6450 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006451#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006452 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006453#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006454 /* We have to sanity check the raw data, otherwise doom looms for
6455 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006456 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006457 endinpos = s - starts + Py_UNICODE_SIZE;
6458 reason = "illegal code point (> 0x10FFFF)";
6459 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006460 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006461#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006462 s += Py_UNICODE_SIZE;
6463#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006464 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006465 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006466 Py_UNICODE uch2;
6467 ((char *) &uch2)[0] = s[0];
6468 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006469 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006470 {
Victor Stinner551ac952011-11-29 22:58:13 +01006471 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006472 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006473 }
6474 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006475#endif
6476
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006477 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006478 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006479 continue;
6480
6481 error:
6482 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006483 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006484 errors, &errorHandler,
6485 "unicode_internal", reason,
6486 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006487 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006488 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489 }
6490
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006491 Py_XDECREF(errorHandler);
6492 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006493 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006494
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006496 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006497 Py_XDECREF(errorHandler);
6498 Py_XDECREF(exc);
6499 return NULL;
6500}
6501
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502/* --- Latin-1 Codec ------------------------------------------------------ */
6503
Alexander Belopolsky40018472011-02-26 01:02:56 +00006504PyObject *
6505PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006506 Py_ssize_t size,
6507 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006510 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511}
6512
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006513/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006514static void
6515make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006516 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006517 PyObject *unicode,
6518 Py_ssize_t startpos, Py_ssize_t endpos,
6519 const char *reason)
6520{
6521 if (*exceptionObject == NULL) {
6522 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006523 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006524 encoding, unicode, startpos, endpos, reason);
6525 }
6526 else {
6527 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6528 goto onError;
6529 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6530 goto onError;
6531 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6532 goto onError;
6533 return;
6534 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006535 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006536 }
6537}
6538
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006539/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006540static void
6541raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006542 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006543 PyObject *unicode,
6544 Py_ssize_t startpos, Py_ssize_t endpos,
6545 const char *reason)
6546{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006547 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006548 encoding, unicode, startpos, endpos, reason);
6549 if (*exceptionObject != NULL)
6550 PyCodec_StrictErrors(*exceptionObject);
6551}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006552
6553/* error handling callback helper:
6554 build arguments, call the callback and check the arguments,
6555 put the result into newpos and return the replacement string, which
6556 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006557static PyObject *
6558unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006559 PyObject **errorHandler,
6560 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006561 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006562 Py_ssize_t startpos, Py_ssize_t endpos,
6563 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006564{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006565 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006566 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006567 PyObject *restuple;
6568 PyObject *resunicode;
6569
6570 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006572 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006574 }
6575
Benjamin Petersonbac79492012-01-14 13:34:47 -05006576 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 return NULL;
6578 len = PyUnicode_GET_LENGTH(unicode);
6579
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006580 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584
6585 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006590 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 Py_DECREF(restuple);
6592 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006593 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006594 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 &resunicode, newpos)) {
6596 Py_DECREF(restuple);
6597 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006598 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006599 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6600 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6601 Py_DECREF(restuple);
6602 return NULL;
6603 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006605 *newpos = len + *newpos;
6606 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006607 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 Py_DECREF(restuple);
6609 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006610 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006611 Py_INCREF(resunicode);
6612 Py_DECREF(restuple);
6613 return resunicode;
6614}
6615
Alexander Belopolsky40018472011-02-26 01:02:56 +00006616static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006618 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006619 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006620{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 /* input state */
6622 Py_ssize_t pos=0, size;
6623 int kind;
6624 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006625 /* pointer into the output */
6626 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006627 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6628 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006629 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006631 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006632 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006633 /* output object */
6634 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635
Benjamin Petersonbac79492012-01-14 13:34:47 -05006636 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 return NULL;
6638 size = PyUnicode_GET_LENGTH(unicode);
6639 kind = PyUnicode_KIND(unicode);
6640 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641 /* allocate enough for a simple encoding without
6642 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006643 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006644 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006645
6646 _PyBytesWriter_Init(&writer);
6647 str = _PyBytesWriter_Alloc(&writer, size);
6648 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006650
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006652 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006655 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006657 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006659 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006661 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006663 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006664 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006666
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006667 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006668 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006669
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006670 /* Only overallocate the buffer if it's not the last write */
6671 writer.overallocate = (collend < size);
6672
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006674 if (error_handler == _Py_ERROR_UNKNOWN)
6675 error_handler = get_error_handler(errors);
6676
6677 switch (error_handler) {
6678 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006679 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006680 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006681
6682 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006683 memset(str, '?', collend - collstart);
6684 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006685 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006686 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006687 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006688 break;
Victor Stinner50149202015-09-22 00:26:54 +02006689
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006690 case _Py_ERROR_BACKSLASHREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006691 /* substract preallocated bytes */
6692 writer.min_size -= (collend - collstart);
6693 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006694 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006695 if (str == NULL)
6696 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006697 pos = collend;
6698 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006699
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006700 case _Py_ERROR_XMLCHARREFREPLACE:
Victor Stinnerad771582015-10-09 12:38:53 +02006701 /* substract preallocated bytes */
6702 writer.min_size -= (collend - collstart);
6703 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006704 unicode, collstart, collend);
6705 if (str == NULL)
6706 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 break;
Victor Stinner50149202015-09-22 00:26:54 +02006709
Victor Stinnerc3713e92015-09-29 12:32:13 +02006710 case _Py_ERROR_SURROGATEESCAPE:
6711 for (i = collstart; i < collend; ++i) {
6712 ch = PyUnicode_READ(kind, data, i);
6713 if (ch < 0xdc80 || 0xdcff < ch) {
6714 /* Not a UTF-8b surrogate */
6715 break;
6716 }
6717 *str++ = (char)(ch - 0xdc00);
6718 ++pos;
6719 }
6720 if (i >= collend)
6721 break;
6722 collstart = pos;
6723 assert(collstart != collend);
6724 /* fallback to general error handling */
6725
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006727 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6728 encoding, reason, unicode, &exc,
6729 collstart, collend, &newpos);
6730 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006732
Victor Stinnerad771582015-10-09 12:38:53 +02006733 /* substract preallocated bytes */
6734 writer.min_size -= 1;
6735
Victor Stinner6bd525b2015-10-09 13:10:05 +02006736 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006737 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006738 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006739 PyBytes_AS_STRING(rep),
6740 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006741 if (str == NULL)
6742 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006743 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006744 else {
6745 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006746
Victor Stinner6bd525b2015-10-09 13:10:05 +02006747 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006749
6750 if (PyUnicode_IS_ASCII(rep)) {
6751 /* Fast path: all characters are smaller than limit */
6752 assert(limit >= 128);
6753 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6754 str = _PyBytesWriter_WriteBytes(&writer, str,
6755 PyUnicode_DATA(rep),
6756 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006758 else {
6759 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6760
6761 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6762 if (str == NULL)
6763 goto onError;
6764
6765 /* check if there is anything unencodable in the
6766 replacement and copy it to the output */
6767 for (i = 0; repsize-->0; ++i, ++str) {
6768 ch = PyUnicode_READ_CHAR(rep, i);
6769 if (ch >= limit) {
6770 raise_encode_exception(&exc, encoding, unicode,
6771 pos, pos+1, reason);
6772 goto onError;
6773 }
6774 *str = (char)ch;
6775 }
6776 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006778 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006779 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006780 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006781
6782 /* If overallocation was disabled, ensure that it was the last
6783 write. Otherwise, we missed an optimization */
6784 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006785 }
6786 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006787
Victor Stinner50149202015-09-22 00:26:54 +02006788 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006789 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006790 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006791
6792 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006793 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006794 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006795 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006796 Py_XDECREF(exc);
6797 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006798}
6799
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006800/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006801PyObject *
6802PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006803 Py_ssize_t size,
6804 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006806 PyObject *result;
6807 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6808 if (unicode == NULL)
6809 return NULL;
6810 result = unicode_encode_ucs1(unicode, errors, 256);
6811 Py_DECREF(unicode);
6812 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813}
6814
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006816_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006817{
6818 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 PyErr_BadArgument();
6820 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006822 if (PyUnicode_READY(unicode) == -1)
6823 return NULL;
6824 /* Fast path: if it is a one-byte string, construct
6825 bytes object directly. */
6826 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6827 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6828 PyUnicode_GET_LENGTH(unicode));
6829 /* Non-Latin-1 characters present. Defer to above function to
6830 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006831 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006832}
6833
6834PyObject*
6835PyUnicode_AsLatin1String(PyObject *unicode)
6836{
6837 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006838}
6839
6840/* --- 7-bit ASCII Codec -------------------------------------------------- */
6841
Alexander Belopolsky40018472011-02-26 01:02:56 +00006842PyObject *
6843PyUnicode_DecodeASCII(const char *s,
6844 Py_ssize_t size,
6845 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006846{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006847 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006848 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006849 int kind;
6850 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006851 Py_ssize_t startinpos;
6852 Py_ssize_t endinpos;
6853 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006855 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006856 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006857 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006858
Guido van Rossumd57fd912000-03-10 22:53:23 +00006859 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006860 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006861
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006863 if (size == 1 && (unsigned char)s[0] < 128)
6864 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006865
Victor Stinner8f674cc2013-04-17 23:02:17 +02006866 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006867 writer.min_length = size;
6868 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006869 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006870
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006871 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006872 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006873 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006874 writer.pos = outpos;
6875 if (writer.pos == size)
6876 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006877
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006878 s += writer.pos;
6879 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006880 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006881 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006883 PyUnicode_WRITE(kind, data, writer.pos, c);
6884 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006885 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006886 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006887 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006888
6889 /* byte outsize range 0x00..0x7f: call the error handler */
6890
6891 if (error_handler == _Py_ERROR_UNKNOWN)
6892 error_handler = get_error_handler(errors);
6893
6894 switch (error_handler)
6895 {
6896 case _Py_ERROR_REPLACE:
6897 case _Py_ERROR_SURROGATEESCAPE:
6898 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006899 but we may switch to UCS2 at the first write */
6900 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6901 goto onError;
6902 kind = writer.kind;
6903 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006904
6905 if (error_handler == _Py_ERROR_REPLACE)
6906 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6907 else
6908 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6909 writer.pos++;
6910 ++s;
6911 break;
6912
6913 case _Py_ERROR_IGNORE:
6914 ++s;
6915 break;
6916
6917 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006918 startinpos = s-starts;
6919 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006920 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006921 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006922 "ascii", "ordinal not in range(128)",
6923 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006924 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006925 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006926 kind = writer.kind;
6927 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006928 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006930 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006931 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006932 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006933
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006935 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006936 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006937 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006938 return NULL;
6939}
6940
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006941/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006942PyObject *
6943PyUnicode_EncodeASCII(const Py_UNICODE *p,
6944 Py_ssize_t size,
6945 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006946{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006947 PyObject *result;
6948 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6949 if (unicode == NULL)
6950 return NULL;
6951 result = unicode_encode_ucs1(unicode, errors, 128);
6952 Py_DECREF(unicode);
6953 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006954}
6955
Alexander Belopolsky40018472011-02-26 01:02:56 +00006956PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006957_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006958{
6959 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006960 PyErr_BadArgument();
6961 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006963 if (PyUnicode_READY(unicode) == -1)
6964 return NULL;
6965 /* Fast path: if it is an ASCII-only string, construct bytes object
6966 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006967 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006968 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6969 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006970 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006971}
6972
6973PyObject *
6974PyUnicode_AsASCIIString(PyObject *unicode)
6975{
6976 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006977}
6978
Victor Stinner99b95382011-07-04 14:23:54 +02006979#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006980
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006981/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006982
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006983#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006984#define NEED_RETRY
6985#endif
6986
Victor Stinner3a50e702011-10-18 21:21:00 +02006987#ifndef WC_ERR_INVALID_CHARS
6988# define WC_ERR_INVALID_CHARS 0x0080
6989#endif
6990
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02006991static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02006992code_page_name(UINT code_page, PyObject **obj)
6993{
6994 *obj = NULL;
6995 if (code_page == CP_ACP)
6996 return "mbcs";
6997 if (code_page == CP_UTF7)
6998 return "CP_UTF7";
6999 if (code_page == CP_UTF8)
7000 return "CP_UTF8";
7001
7002 *obj = PyBytes_FromFormat("cp%u", code_page);
7003 if (*obj == NULL)
7004 return NULL;
7005 return PyBytes_AS_STRING(*obj);
7006}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007007
Victor Stinner3a50e702011-10-18 21:21:00 +02007008static DWORD
7009decode_code_page_flags(UINT code_page)
7010{
7011 if (code_page == CP_UTF7) {
7012 /* The CP_UTF7 decoder only supports flags=0 */
7013 return 0;
7014 }
7015 else
7016 return MB_ERR_INVALID_CHARS;
7017}
7018
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007019/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007020 * Decode a byte string from a Windows code page into unicode object in strict
7021 * mode.
7022 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007023 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7024 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007027decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007028 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007029 const char *in,
7030 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031{
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007033 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007034 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035
7036 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007037 assert(insize > 0);
7038 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7039 if (outsize <= 0)
7040 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041
7042 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007043 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007044 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007045 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007046 if (*v == NULL)
7047 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049 }
7050 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007051 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007052 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007053 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007054 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007055 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007056 }
7057
7058 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007059 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7060 if (outsize <= 0)
7061 goto error;
7062 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064error:
7065 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7066 return -2;
7067 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007068 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069}
7070
Victor Stinner3a50e702011-10-18 21:21:00 +02007071/*
7072 * Decode a byte string from a code page into unicode object with an error
7073 * handler.
7074 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007075 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 * UnicodeDecodeError exception and returns -1 on error.
7077 */
7078static int
7079decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 PyObject **v,
7081 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007082 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007083{
7084 const char *startin = in;
7085 const char *endin = in + size;
7086 const DWORD flags = decode_code_page_flags(code_page);
7087 /* Ideally, we should get reason from FormatMessage. This is the Windows
7088 2000 English version of the message. */
7089 const char *reason = "No mapping for the Unicode character exists "
7090 "in the target code page.";
7091 /* each step cannot decode more than 1 character, but a character can be
7092 represented as a surrogate pair */
7093 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007094 int insize;
7095 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007096 PyObject *errorHandler = NULL;
7097 PyObject *exc = NULL;
7098 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007099 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007100 DWORD err;
7101 int ret = -1;
7102
7103 assert(size > 0);
7104
7105 encoding = code_page_name(code_page, &encoding_obj);
7106 if (encoding == NULL)
7107 return -1;
7108
Victor Stinner7d00cc12014-03-17 23:08:06 +01007109 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007110 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7111 UnicodeDecodeError. */
7112 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7113 if (exc != NULL) {
7114 PyCodec_StrictErrors(exc);
7115 Py_CLEAR(exc);
7116 }
7117 goto error;
7118 }
7119
7120 if (*v == NULL) {
7121 /* Create unicode object */
7122 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7123 PyErr_NoMemory();
7124 goto error;
7125 }
Victor Stinnerab595942011-12-17 04:59:06 +01007126 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007127 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007128 if (*v == NULL)
7129 goto error;
7130 startout = PyUnicode_AS_UNICODE(*v);
7131 }
7132 else {
7133 /* Extend unicode object */
7134 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7135 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7136 PyErr_NoMemory();
7137 goto error;
7138 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007139 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 goto error;
7141 startout = PyUnicode_AS_UNICODE(*v) + n;
7142 }
7143
7144 /* Decode the byte string character per character */
7145 out = startout;
7146 while (in < endin)
7147 {
7148 /* Decode a character */
7149 insize = 1;
7150 do
7151 {
7152 outsize = MultiByteToWideChar(code_page, flags,
7153 in, insize,
7154 buffer, Py_ARRAY_LENGTH(buffer));
7155 if (outsize > 0)
7156 break;
7157 err = GetLastError();
7158 if (err != ERROR_NO_UNICODE_TRANSLATION
7159 && err != ERROR_INSUFFICIENT_BUFFER)
7160 {
7161 PyErr_SetFromWindowsErr(0);
7162 goto error;
7163 }
7164 insize++;
7165 }
7166 /* 4=maximum length of a UTF-8 sequence */
7167 while (insize <= 4 && (in + insize) <= endin);
7168
7169 if (outsize <= 0) {
7170 Py_ssize_t startinpos, endinpos, outpos;
7171
Victor Stinner7d00cc12014-03-17 23:08:06 +01007172 /* last character in partial decode? */
7173 if (in + insize >= endin && !final)
7174 break;
7175
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 startinpos = in - startin;
7177 endinpos = startinpos + 1;
7178 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007179 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 errors, &errorHandler,
7181 encoding, reason,
7182 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007183 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 {
7185 goto error;
7186 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007187 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 }
7189 else {
7190 in += insize;
7191 memcpy(out, buffer, outsize * sizeof(wchar_t));
7192 out += outsize;
7193 }
7194 }
7195
7196 /* write a NUL character at the end */
7197 *out = 0;
7198
7199 /* Extend unicode object */
7200 outsize = out - startout;
7201 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007202 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007203 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007204 /* (in - startin) <= size and size is an int */
7205 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007206
7207error:
7208 Py_XDECREF(encoding_obj);
7209 Py_XDECREF(errorHandler);
7210 Py_XDECREF(exc);
7211 return ret;
7212}
7213
Victor Stinner3a50e702011-10-18 21:21:00 +02007214static PyObject *
7215decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007216 const char *s, Py_ssize_t size,
7217 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007218{
Victor Stinner76a31a62011-11-04 00:05:13 +01007219 PyObject *v = NULL;
7220 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007221
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 if (code_page < 0) {
7223 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7224 return NULL;
7225 }
7226
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007227 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007228 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007229
Victor Stinner76a31a62011-11-04 00:05:13 +01007230 do
7231 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007232#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007233 if (size > INT_MAX) {
7234 chunk_size = INT_MAX;
7235 final = 0;
7236 done = 0;
7237 }
7238 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007239#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007240 {
7241 chunk_size = (int)size;
7242 final = (consumed == NULL);
7243 done = 1;
7244 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007245
Victor Stinner76a31a62011-11-04 00:05:13 +01007246 if (chunk_size == 0 && done) {
7247 if (v != NULL)
7248 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007249 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251
Victor Stinner76a31a62011-11-04 00:05:13 +01007252 converted = decode_code_page_strict(code_page, &v,
7253 s, chunk_size);
7254 if (converted == -2)
7255 converted = decode_code_page_errors(code_page, &v,
7256 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007257 errors, final);
7258 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007259
7260 if (converted < 0) {
7261 Py_XDECREF(v);
7262 return NULL;
7263 }
7264
7265 if (consumed)
7266 *consumed += converted;
7267
7268 s += converted;
7269 size -= converted;
7270 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007271
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007272 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273}
7274
Alexander Belopolsky40018472011-02-26 01:02:56 +00007275PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007276PyUnicode_DecodeCodePageStateful(int code_page,
7277 const char *s,
7278 Py_ssize_t size,
7279 const char *errors,
7280 Py_ssize_t *consumed)
7281{
7282 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7283}
7284
7285PyObject *
7286PyUnicode_DecodeMBCSStateful(const char *s,
7287 Py_ssize_t size,
7288 const char *errors,
7289 Py_ssize_t *consumed)
7290{
7291 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7292}
7293
7294PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007295PyUnicode_DecodeMBCS(const char *s,
7296 Py_ssize_t size,
7297 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007298{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007299 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7300}
7301
Victor Stinner3a50e702011-10-18 21:21:00 +02007302static DWORD
7303encode_code_page_flags(UINT code_page, const char *errors)
7304{
7305 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007306 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007307 }
7308 else if (code_page == CP_UTF7) {
7309 /* CP_UTF7 only supports flags=0 */
7310 return 0;
7311 }
7312 else {
7313 if (errors != NULL && strcmp(errors, "replace") == 0)
7314 return 0;
7315 else
7316 return WC_NO_BEST_FIT_CHARS;
7317 }
7318}
7319
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007320/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 * Encode a Unicode string to a Windows code page into a byte string in strict
7322 * mode.
7323 *
7324 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007325 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007326 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007327static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007328encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007329 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331{
Victor Stinner554f3f02010-06-16 23:33:54 +00007332 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007333 BOOL *pusedDefaultChar = &usedDefaultChar;
7334 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007335 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007336 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 const DWORD flags = encode_code_page_flags(code_page, NULL);
7338 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007339 /* Create a substring so that we can get the UTF-16 representation
7340 of just the slice under consideration. */
7341 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007344
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007346 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007347 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007348 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007349
Victor Stinner2fc507f2011-11-04 20:06:39 +01007350 substring = PyUnicode_Substring(unicode, offset, offset+len);
7351 if (substring == NULL)
7352 return -1;
7353 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7354 if (p == NULL) {
7355 Py_DECREF(substring);
7356 return -1;
7357 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007358 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007360 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007362 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007363 NULL, 0,
7364 NULL, pusedDefaultChar);
7365 if (outsize <= 0)
7366 goto error;
7367 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007368 if (pusedDefaultChar && *pusedDefaultChar) {
7369 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007370 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007371 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007372
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007374 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007376 if (*outbytes == NULL) {
7377 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007378 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007379 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007381 }
7382 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007383 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const Py_ssize_t n = PyBytes_Size(*outbytes);
7385 if (outsize > PY_SSIZE_T_MAX - n) {
7386 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007387 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007388 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007389 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007390 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7391 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007393 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007395 }
7396
7397 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007399 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 out, outsize,
7401 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007402 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 if (outsize <= 0)
7404 goto error;
7405 if (pusedDefaultChar && *pusedDefaultChar)
7406 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007407 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007408
Victor Stinner3a50e702011-10-18 21:21:00 +02007409error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007410 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7412 return -2;
7413 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007414 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007415}
7416
Victor Stinner3a50e702011-10-18 21:21:00 +02007417/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007418 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 * error handler.
7420 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007421 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 * -1 on other error.
7423 */
7424static int
7425encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007426 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007427 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007428{
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007430 Py_ssize_t pos = unicode_offset;
7431 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 /* Ideally, we should get reason from FormatMessage. This is the Windows
7433 2000 English version of the message. */
7434 const char *reason = "invalid character";
7435 /* 4=maximum length of a UTF-8 sequence */
7436 char buffer[4];
7437 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7438 Py_ssize_t outsize;
7439 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 PyObject *errorHandler = NULL;
7441 PyObject *exc = NULL;
7442 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007443 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007444 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 PyObject *rep;
7446 int ret = -1;
7447
7448 assert(insize > 0);
7449
7450 encoding = code_page_name(code_page, &encoding_obj);
7451 if (encoding == NULL)
7452 return -1;
7453
7454 if (errors == NULL || strcmp(errors, "strict") == 0) {
7455 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7456 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007457 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 if (exc != NULL) {
7459 PyCodec_StrictErrors(exc);
7460 Py_DECREF(exc);
7461 }
7462 Py_XDECREF(encoding_obj);
7463 return -1;
7464 }
7465
7466 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7467 pusedDefaultChar = &usedDefaultChar;
7468 else
7469 pusedDefaultChar = NULL;
7470
7471 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7472 PyErr_NoMemory();
7473 goto error;
7474 }
7475 outsize = insize * Py_ARRAY_LENGTH(buffer);
7476
7477 if (*outbytes == NULL) {
7478 /* Create string object */
7479 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7480 if (*outbytes == NULL)
7481 goto error;
7482 out = PyBytes_AS_STRING(*outbytes);
7483 }
7484 else {
7485 /* Extend string object */
7486 Py_ssize_t n = PyBytes_Size(*outbytes);
7487 if (n > PY_SSIZE_T_MAX - outsize) {
7488 PyErr_NoMemory();
7489 goto error;
7490 }
7491 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7492 goto error;
7493 out = PyBytes_AS_STRING(*outbytes) + n;
7494 }
7495
7496 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007499 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7500 wchar_t chars[2];
7501 int charsize;
7502 if (ch < 0x10000) {
7503 chars[0] = (wchar_t)ch;
7504 charsize = 1;
7505 }
7506 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007507 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7508 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007509 charsize = 2;
7510 }
7511
Victor Stinner3a50e702011-10-18 21:21:00 +02007512 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007513 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007514 buffer, Py_ARRAY_LENGTH(buffer),
7515 NULL, pusedDefaultChar);
7516 if (outsize > 0) {
7517 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7518 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007519 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007520 memcpy(out, buffer, outsize);
7521 out += outsize;
7522 continue;
7523 }
7524 }
7525 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7526 PyErr_SetFromWindowsErr(0);
7527 goto error;
7528 }
7529
Victor Stinner3a50e702011-10-18 21:21:00 +02007530 rep = unicode_encode_call_errorhandler(
7531 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007532 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007533 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007534 if (rep == NULL)
7535 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007536 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007537
7538 if (PyBytes_Check(rep)) {
7539 outsize = PyBytes_GET_SIZE(rep);
7540 if (outsize != 1) {
7541 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7542 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7543 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7544 Py_DECREF(rep);
7545 goto error;
7546 }
7547 out = PyBytes_AS_STRING(*outbytes) + offset;
7548 }
7549 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7550 out += outsize;
7551 }
7552 else {
7553 Py_ssize_t i;
7554 enum PyUnicode_Kind kind;
7555 void *data;
7556
Benjamin Petersonbac79492012-01-14 13:34:47 -05007557 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007558 Py_DECREF(rep);
7559 goto error;
7560 }
7561
7562 outsize = PyUnicode_GET_LENGTH(rep);
7563 if (outsize != 1) {
7564 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7565 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7566 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7567 Py_DECREF(rep);
7568 goto error;
7569 }
7570 out = PyBytes_AS_STRING(*outbytes) + offset;
7571 }
7572 kind = PyUnicode_KIND(rep);
7573 data = PyUnicode_DATA(rep);
7574 for (i=0; i < outsize; i++) {
7575 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7576 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007577 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007578 encoding, unicode,
7579 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 "unable to encode error handler result to ASCII");
7581 Py_DECREF(rep);
7582 goto error;
7583 }
7584 *out = (unsigned char)ch;
7585 out++;
7586 }
7587 }
7588 Py_DECREF(rep);
7589 }
7590 /* write a NUL byte */
7591 *out = 0;
7592 outsize = out - PyBytes_AS_STRING(*outbytes);
7593 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7594 if (_PyBytes_Resize(outbytes, outsize) < 0)
7595 goto error;
7596 ret = 0;
7597
7598error:
7599 Py_XDECREF(encoding_obj);
7600 Py_XDECREF(errorHandler);
7601 Py_XDECREF(exc);
7602 return ret;
7603}
7604
Victor Stinner3a50e702011-10-18 21:21:00 +02007605static PyObject *
7606encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007607 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007608 const char *errors)
7609{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007610 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007611 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007612 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007613 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007614
Victor Stinner29dacf22015-01-26 16:41:32 +01007615 if (!PyUnicode_Check(unicode)) {
7616 PyErr_BadArgument();
7617 return NULL;
7618 }
7619
Benjamin Petersonbac79492012-01-14 13:34:47 -05007620 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007621 return NULL;
7622 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007623
Victor Stinner3a50e702011-10-18 21:21:00 +02007624 if (code_page < 0) {
7625 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7626 return NULL;
7627 }
7628
Martin v. Löwis3d325192011-11-04 18:23:06 +01007629 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007630 return PyBytes_FromStringAndSize(NULL, 0);
7631
Victor Stinner7581cef2011-11-03 22:32:33 +01007632 offset = 0;
7633 do
7634 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007635#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007636 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007637 chunks. */
7638 if (len > INT_MAX/2) {
7639 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007640 done = 0;
7641 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007642 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007643#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007644 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007645 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007646 done = 1;
7647 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007648
Victor Stinner76a31a62011-11-04 00:05:13 +01007649 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007650 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007651 errors);
7652 if (ret == -2)
7653 ret = encode_code_page_errors(code_page, &outbytes,
7654 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007655 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007656 if (ret < 0) {
7657 Py_XDECREF(outbytes);
7658 return NULL;
7659 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007660
Victor Stinner7581cef2011-11-03 22:32:33 +01007661 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007662 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007663 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007664
Victor Stinner3a50e702011-10-18 21:21:00 +02007665 return outbytes;
7666}
7667
7668PyObject *
7669PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7670 Py_ssize_t size,
7671 const char *errors)
7672{
Victor Stinner7581cef2011-11-03 22:32:33 +01007673 PyObject *unicode, *res;
7674 unicode = PyUnicode_FromUnicode(p, size);
7675 if (unicode == NULL)
7676 return NULL;
7677 res = encode_code_page(CP_ACP, unicode, errors);
7678 Py_DECREF(unicode);
7679 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007680}
7681
7682PyObject *
7683PyUnicode_EncodeCodePage(int code_page,
7684 PyObject *unicode,
7685 const char *errors)
7686{
Victor Stinner7581cef2011-11-03 22:32:33 +01007687 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007688}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007689
Alexander Belopolsky40018472011-02-26 01:02:56 +00007690PyObject *
7691PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007692{
Victor Stinner7581cef2011-11-03 22:32:33 +01007693 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007694}
7695
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007696#undef NEED_RETRY
7697
Victor Stinner99b95382011-07-04 14:23:54 +02007698#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007699
Guido van Rossumd57fd912000-03-10 22:53:23 +00007700/* --- Character Mapping Codec -------------------------------------------- */
7701
Victor Stinnerfb161b12013-04-18 01:44:27 +02007702static int
7703charmap_decode_string(const char *s,
7704 Py_ssize_t size,
7705 PyObject *mapping,
7706 const char *errors,
7707 _PyUnicodeWriter *writer)
7708{
7709 const char *starts = s;
7710 const char *e;
7711 Py_ssize_t startinpos, endinpos;
7712 PyObject *errorHandler = NULL, *exc = NULL;
7713 Py_ssize_t maplen;
7714 enum PyUnicode_Kind mapkind;
7715 void *mapdata;
7716 Py_UCS4 x;
7717 unsigned char ch;
7718
7719 if (PyUnicode_READY(mapping) == -1)
7720 return -1;
7721
7722 maplen = PyUnicode_GET_LENGTH(mapping);
7723 mapdata = PyUnicode_DATA(mapping);
7724 mapkind = PyUnicode_KIND(mapping);
7725
7726 e = s + size;
7727
7728 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7729 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7730 * is disabled in encoding aliases, latin1 is preferred because
7731 * its implementation is faster. */
7732 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7733 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7734 Py_UCS4 maxchar = writer->maxchar;
7735
7736 assert (writer->kind == PyUnicode_1BYTE_KIND);
7737 while (s < e) {
7738 ch = *s;
7739 x = mapdata_ucs1[ch];
7740 if (x > maxchar) {
7741 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7742 goto onError;
7743 maxchar = writer->maxchar;
7744 outdata = (Py_UCS1 *)writer->data;
7745 }
7746 outdata[writer->pos] = x;
7747 writer->pos++;
7748 ++s;
7749 }
7750 return 0;
7751 }
7752
7753 while (s < e) {
7754 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7755 enum PyUnicode_Kind outkind = writer->kind;
7756 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7757 if (outkind == PyUnicode_1BYTE_KIND) {
7758 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7759 Py_UCS4 maxchar = writer->maxchar;
7760 while (s < e) {
7761 ch = *s;
7762 x = mapdata_ucs2[ch];
7763 if (x > maxchar)
7764 goto Error;
7765 outdata[writer->pos] = x;
7766 writer->pos++;
7767 ++s;
7768 }
7769 break;
7770 }
7771 else if (outkind == PyUnicode_2BYTE_KIND) {
7772 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7773 while (s < e) {
7774 ch = *s;
7775 x = mapdata_ucs2[ch];
7776 if (x == 0xFFFE)
7777 goto Error;
7778 outdata[writer->pos] = x;
7779 writer->pos++;
7780 ++s;
7781 }
7782 break;
7783 }
7784 }
7785 ch = *s;
7786
7787 if (ch < maplen)
7788 x = PyUnicode_READ(mapkind, mapdata, ch);
7789 else
7790 x = 0xfffe; /* invalid value */
7791Error:
7792 if (x == 0xfffe)
7793 {
7794 /* undefined mapping */
7795 startinpos = s-starts;
7796 endinpos = startinpos+1;
7797 if (unicode_decode_call_errorhandler_writer(
7798 errors, &errorHandler,
7799 "charmap", "character maps to <undefined>",
7800 &starts, &e, &startinpos, &endinpos, &exc, &s,
7801 writer)) {
7802 goto onError;
7803 }
7804 continue;
7805 }
7806
7807 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7808 goto onError;
7809 ++s;
7810 }
7811 Py_XDECREF(errorHandler);
7812 Py_XDECREF(exc);
7813 return 0;
7814
7815onError:
7816 Py_XDECREF(errorHandler);
7817 Py_XDECREF(exc);
7818 return -1;
7819}
7820
7821static int
7822charmap_decode_mapping(const char *s,
7823 Py_ssize_t size,
7824 PyObject *mapping,
7825 const char *errors,
7826 _PyUnicodeWriter *writer)
7827{
7828 const char *starts = s;
7829 const char *e;
7830 Py_ssize_t startinpos, endinpos;
7831 PyObject *errorHandler = NULL, *exc = NULL;
7832 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007833 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007834
7835 e = s + size;
7836
7837 while (s < e) {
7838 ch = *s;
7839
7840 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7841 key = PyLong_FromLong((long)ch);
7842 if (key == NULL)
7843 goto onError;
7844
7845 item = PyObject_GetItem(mapping, key);
7846 Py_DECREF(key);
7847 if (item == NULL) {
7848 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7849 /* No mapping found means: mapping is undefined. */
7850 PyErr_Clear();
7851 goto Undefined;
7852 } else
7853 goto onError;
7854 }
7855
7856 /* Apply mapping */
7857 if (item == Py_None)
7858 goto Undefined;
7859 if (PyLong_Check(item)) {
7860 long value = PyLong_AS_LONG(item);
7861 if (value == 0xFFFE)
7862 goto Undefined;
7863 if (value < 0 || value > MAX_UNICODE) {
7864 PyErr_Format(PyExc_TypeError,
7865 "character mapping must be in range(0x%lx)",
7866 (unsigned long)MAX_UNICODE + 1);
7867 goto onError;
7868 }
7869
7870 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7871 goto onError;
7872 }
7873 else if (PyUnicode_Check(item)) {
7874 if (PyUnicode_READY(item) == -1)
7875 goto onError;
7876 if (PyUnicode_GET_LENGTH(item) == 1) {
7877 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7878 if (value == 0xFFFE)
7879 goto Undefined;
7880 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7881 goto onError;
7882 }
7883 else {
7884 writer->overallocate = 1;
7885 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7886 goto onError;
7887 }
7888 }
7889 else {
7890 /* wrong return value */
7891 PyErr_SetString(PyExc_TypeError,
7892 "character mapping must return integer, None or str");
7893 goto onError;
7894 }
7895 Py_CLEAR(item);
7896 ++s;
7897 continue;
7898
7899Undefined:
7900 /* undefined mapping */
7901 Py_CLEAR(item);
7902 startinpos = s-starts;
7903 endinpos = startinpos+1;
7904 if (unicode_decode_call_errorhandler_writer(
7905 errors, &errorHandler,
7906 "charmap", "character maps to <undefined>",
7907 &starts, &e, &startinpos, &endinpos, &exc, &s,
7908 writer)) {
7909 goto onError;
7910 }
7911 }
7912 Py_XDECREF(errorHandler);
7913 Py_XDECREF(exc);
7914 return 0;
7915
7916onError:
7917 Py_XDECREF(item);
7918 Py_XDECREF(errorHandler);
7919 Py_XDECREF(exc);
7920 return -1;
7921}
7922
Alexander Belopolsky40018472011-02-26 01:02:56 +00007923PyObject *
7924PyUnicode_DecodeCharmap(const char *s,
7925 Py_ssize_t size,
7926 PyObject *mapping,
7927 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007928{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007929 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007930
Guido van Rossumd57fd912000-03-10 22:53:23 +00007931 /* Default to Latin-1 */
7932 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007933 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007934
Guido van Rossumd57fd912000-03-10 22:53:23 +00007935 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007936 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007937 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007938 writer.min_length = size;
7939 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007940 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007941
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007942 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007943 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7944 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007945 }
7946 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007947 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7948 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007949 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007950 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007951
Benjamin Peterson29060642009-01-31 22:14:21 +00007952 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007953 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007954 return NULL;
7955}
7956
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007957/* Charmap encoding: the lookup table */
7958
Alexander Belopolsky40018472011-02-26 01:02:56 +00007959struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 PyObject_HEAD
7961 unsigned char level1[32];
7962 int count2, count3;
7963 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964};
7965
7966static PyObject*
7967encoding_map_size(PyObject *obj, PyObject* args)
7968{
7969 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007970 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007972}
7973
7974static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007975 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007976 PyDoc_STR("Return the size (in bytes) of this object") },
7977 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007978};
7979
7980static void
7981encoding_map_dealloc(PyObject* o)
7982{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007983 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007984}
7985
7986static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007987 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 "EncodingMap", /*tp_name*/
7989 sizeof(struct encoding_map), /*tp_basicsize*/
7990 0, /*tp_itemsize*/
7991 /* methods */
7992 encoding_map_dealloc, /*tp_dealloc*/
7993 0, /*tp_print*/
7994 0, /*tp_getattr*/
7995 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007996 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 0, /*tp_repr*/
7998 0, /*tp_as_number*/
7999 0, /*tp_as_sequence*/
8000 0, /*tp_as_mapping*/
8001 0, /*tp_hash*/
8002 0, /*tp_call*/
8003 0, /*tp_str*/
8004 0, /*tp_getattro*/
8005 0, /*tp_setattro*/
8006 0, /*tp_as_buffer*/
8007 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8008 0, /*tp_doc*/
8009 0, /*tp_traverse*/
8010 0, /*tp_clear*/
8011 0, /*tp_richcompare*/
8012 0, /*tp_weaklistoffset*/
8013 0, /*tp_iter*/
8014 0, /*tp_iternext*/
8015 encoding_map_methods, /*tp_methods*/
8016 0, /*tp_members*/
8017 0, /*tp_getset*/
8018 0, /*tp_base*/
8019 0, /*tp_dict*/
8020 0, /*tp_descr_get*/
8021 0, /*tp_descr_set*/
8022 0, /*tp_dictoffset*/
8023 0, /*tp_init*/
8024 0, /*tp_alloc*/
8025 0, /*tp_new*/
8026 0, /*tp_free*/
8027 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028};
8029
8030PyObject*
8031PyUnicode_BuildEncodingMap(PyObject* string)
8032{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 PyObject *result;
8034 struct encoding_map *mresult;
8035 int i;
8036 int need_dict = 0;
8037 unsigned char level1[32];
8038 unsigned char level2[512];
8039 unsigned char *mlevel1, *mlevel2, *mlevel3;
8040 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008041 int kind;
8042 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008043 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008044 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008046 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047 PyErr_BadArgument();
8048 return NULL;
8049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008050 kind = PyUnicode_KIND(string);
8051 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008052 length = PyUnicode_GET_LENGTH(string);
8053 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 memset(level1, 0xFF, sizeof level1);
8055 memset(level2, 0xFF, sizeof level2);
8056
8057 /* If there isn't a one-to-one mapping of NULL to \0,
8058 or if there are non-BMP characters, we need to use
8059 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008060 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008061 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008062 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008064 ch = PyUnicode_READ(kind, data, i);
8065 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008066 need_dict = 1;
8067 break;
8068 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008069 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070 /* unmapped character */
8071 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008072 l1 = ch >> 11;
8073 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008074 if (level1[l1] == 0xFF)
8075 level1[l1] = count2++;
8076 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008077 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 }
8079
8080 if (count2 >= 0xFF || count3 >= 0xFF)
8081 need_dict = 1;
8082
8083 if (need_dict) {
8084 PyObject *result = PyDict_New();
8085 PyObject *key, *value;
8086 if (!result)
8087 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008088 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008090 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091 if (!key || !value)
8092 goto failed1;
8093 if (PyDict_SetItem(result, key, value) == -1)
8094 goto failed1;
8095 Py_DECREF(key);
8096 Py_DECREF(value);
8097 }
8098 return result;
8099 failed1:
8100 Py_XDECREF(key);
8101 Py_XDECREF(value);
8102 Py_DECREF(result);
8103 return NULL;
8104 }
8105
8106 /* Create a three-level trie */
8107 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8108 16*count2 + 128*count3 - 1);
8109 if (!result)
8110 return PyErr_NoMemory();
8111 PyObject_Init(result, &EncodingMapType);
8112 mresult = (struct encoding_map*)result;
8113 mresult->count2 = count2;
8114 mresult->count3 = count3;
8115 mlevel1 = mresult->level1;
8116 mlevel2 = mresult->level23;
8117 mlevel3 = mresult->level23 + 16*count2;
8118 memcpy(mlevel1, level1, 32);
8119 memset(mlevel2, 0xFF, 16*count2);
8120 memset(mlevel3, 0, 128*count3);
8121 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008124 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8125 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 /* unmapped character */
8127 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008128 o1 = ch>>11;
8129 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 i2 = 16*mlevel1[o1] + o2;
8131 if (mlevel2[i2] == 0xFF)
8132 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008133 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 i3 = 128*mlevel2[i2] + o3;
8135 mlevel3[i3] = i;
8136 }
8137 return result;
8138}
8139
8140static int
Victor Stinner22168992011-11-20 17:09:18 +01008141encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008142{
8143 struct encoding_map *map = (struct encoding_map*)mapping;
8144 int l1 = c>>11;
8145 int l2 = (c>>7) & 0xF;
8146 int l3 = c & 0x7F;
8147 int i;
8148
Victor Stinner22168992011-11-20 17:09:18 +01008149 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151 if (c == 0)
8152 return 0;
8153 /* level 1*/
8154 i = map->level1[l1];
8155 if (i == 0xFF) {
8156 return -1;
8157 }
8158 /* level 2*/
8159 i = map->level23[16*i+l2];
8160 if (i == 0xFF) {
8161 return -1;
8162 }
8163 /* level 3 */
8164 i = map->level23[16*map->count2 + 128*i + l3];
8165 if (i == 0) {
8166 return -1;
8167 }
8168 return i;
8169}
8170
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171/* Lookup the character ch in the mapping. If the character
8172 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008173 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008174static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008175charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008176{
Christian Heimes217cfd12007-12-02 14:31:20 +00008177 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178 PyObject *x;
8179
8180 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008181 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008182 x = PyObject_GetItem(mapping, w);
8183 Py_DECREF(w);
8184 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8186 /* No mapping found means: mapping is undefined. */
8187 PyErr_Clear();
8188 x = Py_None;
8189 Py_INCREF(x);
8190 return x;
8191 } else
8192 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008193 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008194 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008196 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 long value = PyLong_AS_LONG(x);
8198 if (value < 0 || value > 255) {
8199 PyErr_SetString(PyExc_TypeError,
8200 "character mapping must be in range(256)");
8201 Py_DECREF(x);
8202 return NULL;
8203 }
8204 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008205 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008206 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008208 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 /* wrong return value */
8210 PyErr_Format(PyExc_TypeError,
8211 "character mapping must return integer, bytes or None, not %.400s",
8212 x->ob_type->tp_name);
8213 Py_DECREF(x);
8214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215 }
8216}
8217
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008218static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008219charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008221 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8222 /* exponentially overallocate to minimize reallocations */
8223 if (requiredsize < 2*outsize)
8224 requiredsize = 2*outsize;
8225 if (_PyBytes_Resize(outobj, requiredsize))
8226 return -1;
8227 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008228}
8229
Benjamin Peterson14339b62009-01-31 16:36:08 +00008230typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008232} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008234 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 space is available. Return a new reference to the object that
8236 was put in the output buffer, or Py_None, if the mapping was undefined
8237 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008238 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008239static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008240charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008241 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008243 PyObject *rep;
8244 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008245 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246
Christian Heimes90aa7642007-12-19 02:45:37 +00008247 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008248 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008250 if (res == -1)
8251 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 if (outsize<requiredsize)
8253 if (charmapencode_resize(outobj, outpos, requiredsize))
8254 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008255 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 outstart[(*outpos)++] = (char)res;
8257 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008258 }
8259
8260 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 Py_DECREF(rep);
8265 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008266 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 if (PyLong_Check(rep)) {
8268 Py_ssize_t requiredsize = *outpos+1;
8269 if (outsize<requiredsize)
8270 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8271 Py_DECREF(rep);
8272 return enc_EXCEPTION;
8273 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008274 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008276 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 else {
8278 const char *repchars = PyBytes_AS_STRING(rep);
8279 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8280 Py_ssize_t requiredsize = *outpos+repsize;
8281 if (outsize<requiredsize)
8282 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8283 Py_DECREF(rep);
8284 return enc_EXCEPTION;
8285 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008286 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 memcpy(outstart + *outpos, repchars, repsize);
8288 *outpos += repsize;
8289 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008291 Py_DECREF(rep);
8292 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293}
8294
8295/* handle an error in PyUnicode_EncodeCharmap
8296 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008297static int
8298charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008299 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008301 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008302 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303{
8304 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008306 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008307 enum PyUnicode_Kind kind;
8308 void *data;
8309 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008310 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008311 Py_ssize_t collstartpos = *inpos;
8312 Py_ssize_t collendpos = *inpos+1;
8313 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 char *encoding = "charmap";
8315 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008316 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008317 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008318 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319
Benjamin Petersonbac79492012-01-14 13:34:47 -05008320 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321 return -1;
8322 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323 /* find all unencodable characters */
8324 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008325 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008326 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008327 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008328 val = encoding_map_lookup(ch, mapping);
8329 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 break;
8331 ++collendpos;
8332 continue;
8333 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008334
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008335 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8336 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 if (rep==NULL)
8338 return -1;
8339 else if (rep!=Py_None) {
8340 Py_DECREF(rep);
8341 break;
8342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008343 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345 }
8346 /* cache callback name lookup
8347 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008348 if (*error_handler == _Py_ERROR_UNKNOWN)
8349 *error_handler = get_error_handler(errors);
8350
8351 switch (*error_handler) {
8352 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008353 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008354 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008355
8356 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 x = charmapencode_output('?', mapping, res, respos);
8359 if (x==enc_EXCEPTION) {
8360 return -1;
8361 }
8362 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008363 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 return -1;
8365 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008366 }
8367 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008368 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008369 *inpos = collendpos;
8370 break;
Victor Stinner50149202015-09-22 00:26:54 +02008371
8372 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008373 /* generate replacement (temporarily (mis)uses p) */
8374 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 char buffer[2+29+1+1];
8376 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008377 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 for (cp = buffer; *cp; ++cp) {
8379 x = charmapencode_output(*cp, mapping, res, respos);
8380 if (x==enc_EXCEPTION)
8381 return -1;
8382 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008383 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 return -1;
8385 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 }
8387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008388 *inpos = collendpos;
8389 break;
Victor Stinner50149202015-09-22 00:26:54 +02008390
Benjamin Peterson14339b62009-01-31 16:36:08 +00008391 default:
Victor Stinner50149202015-09-22 00:26:54 +02008392 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008393 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008395 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008397 if (PyBytes_Check(repunicode)) {
8398 /* Directly copy bytes result to output. */
8399 Py_ssize_t outsize = PyBytes_Size(*res);
8400 Py_ssize_t requiredsize;
8401 repsize = PyBytes_Size(repunicode);
8402 requiredsize = *respos + repsize;
8403 if (requiredsize > outsize)
8404 /* Make room for all additional bytes. */
8405 if (charmapencode_resize(res, respos, requiredsize)) {
8406 Py_DECREF(repunicode);
8407 return -1;
8408 }
8409 memcpy(PyBytes_AsString(*res) + *respos,
8410 PyBytes_AsString(repunicode), repsize);
8411 *respos += repsize;
8412 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008413 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008414 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008415 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008417 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008418 Py_DECREF(repunicode);
8419 return -1;
8420 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008421 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008422 data = PyUnicode_DATA(repunicode);
8423 kind = PyUnicode_KIND(repunicode);
8424 for (index = 0; index < repsize; index++) {
8425 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8426 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008428 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 return -1;
8430 }
8431 else if (x==enc_FAILED) {
8432 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008433 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 return -1;
8435 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 }
8437 *inpos = newpos;
8438 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439 }
8440 return 0;
8441}
8442
Alexander Belopolsky40018472011-02-26 01:02:56 +00008443PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008444_PyUnicode_EncodeCharmap(PyObject *unicode,
8445 PyObject *mapping,
8446 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008447{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 /* output object */
8449 PyObject *res = NULL;
8450 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008451 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008452 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008454 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008455 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008457 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008458 void *data;
8459 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008460
Benjamin Petersonbac79492012-01-14 13:34:47 -05008461 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008462 return NULL;
8463 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008464 data = PyUnicode_DATA(unicode);
8465 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008466
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467 /* Default to Latin-1 */
8468 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008469 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008470
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 /* allocate enough for a simple encoding without
8472 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008473 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 if (res == NULL)
8475 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008476 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008480 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008482 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 if (x==enc_EXCEPTION) /* error */
8484 goto onError;
8485 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008486 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008488 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 &res, &respos)) {
8490 goto onError;
8491 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 else
8494 /* done with this character => adjust input position */
8495 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008497
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008499 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008500 if (_PyBytes_Resize(&res, respos) < 0)
8501 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008502
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008504 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505 return res;
8506
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508 Py_XDECREF(res);
8509 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008510 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008511 return NULL;
8512}
8513
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514/* Deprecated */
8515PyObject *
8516PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8517 Py_ssize_t size,
8518 PyObject *mapping,
8519 const char *errors)
8520{
8521 PyObject *result;
8522 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8523 if (unicode == NULL)
8524 return NULL;
8525 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8526 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008527 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528}
8529
Alexander Belopolsky40018472011-02-26 01:02:56 +00008530PyObject *
8531PyUnicode_AsCharmapString(PyObject *unicode,
8532 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008533{
8534 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 PyErr_BadArgument();
8536 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008537 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008538 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539}
8540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008542static void
8543make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008545 Py_ssize_t startpos, Py_ssize_t endpos,
8546 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008547{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 *exceptionObject = _PyUnicodeTranslateError_Create(
8550 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008551 }
8552 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8554 goto onError;
8555 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8556 goto onError;
8557 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8558 goto onError;
8559 return;
8560 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008561 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008562 }
8563}
8564
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565/* error handling callback helper:
8566 build arguments, call the callback and check the arguments,
8567 put the result into newpos and return the replacement string, which
8568 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008569static PyObject *
8570unicode_translate_call_errorhandler(const char *errors,
8571 PyObject **errorHandler,
8572 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008574 Py_ssize_t startpos, Py_ssize_t endpos,
8575 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008577 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008579 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 PyObject *restuple;
8581 PyObject *resunicode;
8582
8583 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 }
8588
8589 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593
8594 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008599 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 Py_DECREF(restuple);
8601 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 }
8603 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 &resunicode, &i_newpos)) {
8605 Py_DECREF(restuple);
8606 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008607 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008608 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008610 else
8611 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008613 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 Py_DECREF(restuple);
8615 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008616 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 Py_INCREF(resunicode);
8618 Py_DECREF(restuple);
8619 return resunicode;
8620}
8621
8622/* Lookup the character ch in the mapping and put the result in result,
8623 which must be decrefed by the caller.
8624 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008625static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627{
Christian Heimes217cfd12007-12-02 14:31:20 +00008628 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629 PyObject *x;
8630
8631 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 x = PyObject_GetItem(mapping, w);
8634 Py_DECREF(w);
8635 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8637 /* No mapping found means: use 1:1 mapping. */
8638 PyErr_Clear();
8639 *result = NULL;
8640 return 0;
8641 } else
8642 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 }
8644 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 *result = x;
8646 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008648 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008650 if (value < 0 || value > MAX_UNICODE) {
8651 PyErr_Format(PyExc_ValueError,
8652 "character mapping must be in range(0x%x)",
8653 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 Py_DECREF(x);
8655 return -1;
8656 }
8657 *result = x;
8658 return 0;
8659 }
8660 else if (PyUnicode_Check(x)) {
8661 *result = x;
8662 return 0;
8663 }
8664 else {
8665 /* wrong return value */
8666 PyErr_SetString(PyExc_TypeError,
8667 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008668 Py_DECREF(x);
8669 return -1;
8670 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671}
Victor Stinner1194ea02014-04-04 19:37:40 +02008672
8673/* lookup the character, write the result into the writer.
8674 Return 1 if the result was written into the writer, return 0 if the mapping
8675 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008676static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008677charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8678 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679{
Victor Stinner1194ea02014-04-04 19:37:40 +02008680 PyObject *item;
8681
8682 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008684
8685 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008687 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008690 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008692
8693 if (item == Py_None) {
8694 Py_DECREF(item);
8695 return 0;
8696 }
8697
8698 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008699 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8700 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8701 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008702 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8703 Py_DECREF(item);
8704 return -1;
8705 }
8706 Py_DECREF(item);
8707 return 1;
8708 }
8709
8710 if (!PyUnicode_Check(item)) {
8711 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008713 }
8714
8715 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8716 Py_DECREF(item);
8717 return -1;
8718 }
8719
8720 Py_DECREF(item);
8721 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722}
8723
Victor Stinner89a76ab2014-04-05 11:44:04 +02008724static int
8725unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8726 Py_UCS1 *translate)
8727{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008728 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008729 int ret = 0;
8730
Victor Stinner89a76ab2014-04-05 11:44:04 +02008731 if (charmaptranslate_lookup(ch, mapping, &item)) {
8732 return -1;
8733 }
8734
8735 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008736 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008737 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008738 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008739 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008740 /* not found => default to 1:1 mapping */
8741 translate[ch] = ch;
8742 return 1;
8743 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008744 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008745 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008746 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8747 used it */
8748 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008749 /* invalid character or character outside ASCII:
8750 skip the fast translate */
8751 goto exit;
8752 }
8753 translate[ch] = (Py_UCS1)replace;
8754 }
8755 else if (PyUnicode_Check(item)) {
8756 Py_UCS4 replace;
8757
8758 if (PyUnicode_READY(item) == -1) {
8759 Py_DECREF(item);
8760 return -1;
8761 }
8762 if (PyUnicode_GET_LENGTH(item) != 1)
8763 goto exit;
8764
8765 replace = PyUnicode_READ_CHAR(item, 0);
8766 if (replace > 127)
8767 goto exit;
8768 translate[ch] = (Py_UCS1)replace;
8769 }
8770 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008771 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772 goto exit;
8773 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008774 ret = 1;
8775
Benjamin Peterson1365de72014-04-07 20:15:41 -04008776 exit:
8777 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008778 return ret;
8779}
8780
8781/* Fast path for ascii => ascii translation. Return 1 if the whole string
8782 was translated into writer, return 0 if the input string was partially
8783 translated into writer, raise an exception and return -1 on error. */
8784static int
8785unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008786 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008787{
Victor Stinner872b2912014-04-05 14:27:07 +02008788 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008789 Py_ssize_t len;
8790 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008791 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008792
8793 if (PyUnicode_READY(input) == -1)
8794 return -1;
8795 if (!PyUnicode_IS_ASCII(input))
8796 return 0;
8797 len = PyUnicode_GET_LENGTH(input);
8798
Victor Stinner872b2912014-04-05 14:27:07 +02008799 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008800
8801 in = PyUnicode_1BYTE_DATA(input);
8802 end = in + len;
8803
8804 assert(PyUnicode_IS_ASCII(writer->buffer));
8805 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8806 out = PyUnicode_1BYTE_DATA(writer->buffer);
8807
Victor Stinner872b2912014-04-05 14:27:07 +02008808 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008809 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008810 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008811 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008812 int translate = unicode_fast_translate_lookup(mapping, ch,
8813 ascii_table);
8814 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008815 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008816 if (translate == 0)
8817 goto exit;
8818 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819 }
Victor Stinner872b2912014-04-05 14:27:07 +02008820 if (ch2 == 0xfe) {
8821 if (ignore)
8822 continue;
8823 goto exit;
8824 }
8825 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008826 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008827 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008828 }
Victor Stinner872b2912014-04-05 14:27:07 +02008829 res = 1;
8830
8831exit:
8832 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8833 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834}
8835
Victor Stinner3222da22015-10-01 22:07:32 +02008836static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008837_PyUnicode_TranslateCharmap(PyObject *input,
8838 PyObject *mapping,
8839 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008840{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008842 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843 Py_ssize_t size, i;
8844 int kind;
8845 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008846 _PyUnicodeWriter writer;
8847 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008848 char *reason = "character maps to <undefined>";
8849 PyObject *errorHandler = NULL;
8850 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008851 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008852 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008853
Guido van Rossumd57fd912000-03-10 22:53:23 +00008854 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008855 PyErr_BadArgument();
8856 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008857 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008859 if (PyUnicode_READY(input) == -1)
8860 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008861 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008862 kind = PyUnicode_KIND(input);
8863 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008864
8865 if (size == 0) {
8866 Py_INCREF(input);
8867 return input;
8868 }
8869
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008870 /* allocate enough for a simple 1:1 translation without
8871 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008872 _PyUnicodeWriter_Init(&writer);
8873 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008874 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008875
Victor Stinner872b2912014-04-05 14:27:07 +02008876 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8877
8878 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008879 if (res < 0) {
8880 _PyUnicodeWriter_Dealloc(&writer);
8881 return NULL;
8882 }
8883 if (res == 1)
8884 return _PyUnicodeWriter_Finish(&writer);
8885
Victor Stinner89a76ab2014-04-05 11:44:04 +02008886 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008887 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008888 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008889 int translate;
8890 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8891 Py_ssize_t newpos;
8892 /* startpos for collecting untranslatable chars */
8893 Py_ssize_t collstart;
8894 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008895 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008896
Victor Stinner1194ea02014-04-04 19:37:40 +02008897 ch = PyUnicode_READ(kind, data, i);
8898 translate = charmaptranslate_output(ch, mapping, &writer);
8899 if (translate < 0)
8900 goto onError;
8901
8902 if (translate != 0) {
8903 /* it worked => adjust input pointer */
8904 ++i;
8905 continue;
8906 }
8907
8908 /* untranslatable character */
8909 collstart = i;
8910 collend = i+1;
8911
8912 /* find all untranslatable characters */
8913 while (collend < size) {
8914 PyObject *x;
8915 ch = PyUnicode_READ(kind, data, collend);
8916 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008917 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008918 Py_XDECREF(x);
8919 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008920 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008921 ++collend;
8922 }
8923
8924 if (ignore) {
8925 i = collend;
8926 }
8927 else {
8928 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8929 reason, input, &exc,
8930 collstart, collend, &newpos);
8931 if (repunicode == NULL)
8932 goto onError;
8933 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008934 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008935 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008936 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008937 Py_DECREF(repunicode);
8938 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008939 }
8940 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008941 Py_XDECREF(exc);
8942 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008943 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944
Benjamin Peterson29060642009-01-31 22:14:21 +00008945 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008946 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008947 Py_XDECREF(exc);
8948 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008949 return NULL;
8950}
8951
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952/* Deprecated. Use PyUnicode_Translate instead. */
8953PyObject *
8954PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8955 Py_ssize_t size,
8956 PyObject *mapping,
8957 const char *errors)
8958{
Christian Heimes5f520f42012-09-11 14:03:25 +02008959 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8961 if (!unicode)
8962 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008963 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8964 Py_DECREF(unicode);
8965 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966}
8967
Alexander Belopolsky40018472011-02-26 01:02:56 +00008968PyObject *
8969PyUnicode_Translate(PyObject *str,
8970 PyObject *mapping,
8971 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008972{
8973 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008974
Guido van Rossumd57fd912000-03-10 22:53:23 +00008975 str = PyUnicode_FromObject(str);
8976 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008977 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008979 Py_DECREF(str);
8980 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008981}
Tim Petersced69f82003-09-16 20:30:58 +00008982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008984fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008985{
8986 /* No need to call PyUnicode_READY(self) because this function is only
8987 called as a callback from fixup() which does it already. */
8988 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8989 const int kind = PyUnicode_KIND(self);
8990 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008991 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008992 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008993 Py_ssize_t i;
8994
8995 for (i = 0; i < len; ++i) {
8996 ch = PyUnicode_READ(kind, data, i);
8997 fixed = 0;
8998 if (ch > 127) {
8999 if (Py_UNICODE_ISSPACE(ch))
9000 fixed = ' ';
9001 else {
9002 const int decimal = Py_UNICODE_TODECIMAL(ch);
9003 if (decimal >= 0)
9004 fixed = '0' + decimal;
9005 }
9006 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009007 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009008 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 PyUnicode_WRITE(kind, data, i, fixed);
9010 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009011 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009012 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014 }
9015
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009016 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009017}
9018
9019PyObject *
9020_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9021{
9022 if (!PyUnicode_Check(unicode)) {
9023 PyErr_BadInternalCall();
9024 return NULL;
9025 }
9026 if (PyUnicode_READY(unicode) == -1)
9027 return NULL;
9028 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9029 /* If the string is already ASCII, just return the same string */
9030 Py_INCREF(unicode);
9031 return unicode;
9032 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009033 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009034}
9035
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009036PyObject *
9037PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9038 Py_ssize_t length)
9039{
Victor Stinnerf0124502011-11-21 23:12:56 +01009040 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009041 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009042 Py_UCS4 maxchar;
9043 enum PyUnicode_Kind kind;
9044 void *data;
9045
Victor Stinner99d7ad02012-02-22 13:37:39 +01009046 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009047 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009048 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009049 if (ch > 127) {
9050 int decimal = Py_UNICODE_TODECIMAL(ch);
9051 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009052 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009053 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009054 }
9055 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009056
9057 /* Copy to a new string */
9058 decimal = PyUnicode_New(length, maxchar);
9059 if (decimal == NULL)
9060 return decimal;
9061 kind = PyUnicode_KIND(decimal);
9062 data = PyUnicode_DATA(decimal);
9063 /* Iterate over code points */
9064 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009065 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009066 if (ch > 127) {
9067 int decimal = Py_UNICODE_TODECIMAL(ch);
9068 if (decimal >= 0)
9069 ch = '0' + decimal;
9070 }
9071 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009073 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009074}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009075/* --- Decimal Encoder ---------------------------------------------------- */
9076
Alexander Belopolsky40018472011-02-26 01:02:56 +00009077int
9078PyUnicode_EncodeDecimal(Py_UNICODE *s,
9079 Py_ssize_t length,
9080 char *output,
9081 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009082{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009083 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009084 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009085 enum PyUnicode_Kind kind;
9086 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009087
9088 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009089 PyErr_BadArgument();
9090 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009091 }
9092
Victor Stinner42bf7752011-11-21 22:52:58 +01009093 unicode = PyUnicode_FromUnicode(s, length);
9094 if (unicode == NULL)
9095 return -1;
9096
Benjamin Petersonbac79492012-01-14 13:34:47 -05009097 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009098 Py_DECREF(unicode);
9099 return -1;
9100 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009101 kind = PyUnicode_KIND(unicode);
9102 data = PyUnicode_DATA(unicode);
9103
Victor Stinnerb84d7232011-11-22 01:50:07 +01009104 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009105 PyObject *exc;
9106 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009108 Py_ssize_t startpos;
9109
9110 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009111
Benjamin Peterson29060642009-01-31 22:14:21 +00009112 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009113 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009114 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009115 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009116 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009117 decimal = Py_UNICODE_TODECIMAL(ch);
9118 if (decimal >= 0) {
9119 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009120 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009121 continue;
9122 }
9123 if (0 < ch && ch < 256) {
9124 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009125 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 continue;
9127 }
Victor Stinner6345be92011-11-25 20:09:01 +01009128
Victor Stinner42bf7752011-11-21 22:52:58 +01009129 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009130 exc = NULL;
9131 raise_encode_exception(&exc, "decimal", unicode,
9132 startpos, startpos+1,
9133 "invalid decimal Unicode string");
9134 Py_XDECREF(exc);
9135 Py_DECREF(unicode);
9136 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009137 }
9138 /* 0-terminate the output string */
9139 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009140 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009141 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009142}
9143
Guido van Rossumd57fd912000-03-10 22:53:23 +00009144/* --- Helpers ------------------------------------------------------------ */
9145
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009146/* helper macro to fixup start/end slice values */
9147#define ADJUST_INDICES(start, end, len) \
9148 if (end > len) \
9149 end = len; \
9150 else if (end < 0) { \
9151 end += len; \
9152 if (end < 0) \
9153 end = 0; \
9154 } \
9155 if (start < 0) { \
9156 start += len; \
9157 if (start < 0) \
9158 start = 0; \
9159 }
9160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009162any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 Py_ssize_t start,
9164 Py_ssize_t end)
9165{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009166 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 void *buf1, *buf2;
9168 Py_ssize_t len1, len2, result;
9169
9170 kind1 = PyUnicode_KIND(s1);
9171 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009172 if (kind1 < kind2)
9173 return -1;
9174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175 len1 = PyUnicode_GET_LENGTH(s1);
9176 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009177 ADJUST_INDICES(start, end, len1);
9178 if (end - start < len2)
9179 return -1;
9180
9181 buf1 = PyUnicode_DATA(s1);
9182 buf2 = PyUnicode_DATA(s2);
9183 if (len2 == 1) {
9184 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9185 result = findchar((const char *)buf1 + kind1*start,
9186 kind1, end - start, ch, direction);
9187 if (result == -1)
9188 return -1;
9189 else
9190 return start + result;
9191 }
9192
9193 if (kind2 != kind1) {
9194 buf2 = _PyUnicode_AsKind(s2, kind1);
9195 if (!buf2)
9196 return -2;
9197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198
Victor Stinner794d5672011-10-10 03:21:36 +02009199 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009200 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009201 case PyUnicode_1BYTE_KIND:
9202 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9203 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9204 else
9205 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9206 break;
9207 case PyUnicode_2BYTE_KIND:
9208 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9209 break;
9210 case PyUnicode_4BYTE_KIND:
9211 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9212 break;
9213 default:
9214 assert(0); result = -2;
9215 }
9216 }
9217 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009218 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009219 case PyUnicode_1BYTE_KIND:
9220 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9221 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9222 else
9223 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9224 break;
9225 case PyUnicode_2BYTE_KIND:
9226 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9227 break;
9228 case PyUnicode_4BYTE_KIND:
9229 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9230 break;
9231 default:
9232 assert(0); result = -2;
9233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 }
9235
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009236 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237 PyMem_Free(buf2);
9238
9239 return result;
9240}
9241
9242Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009243_PyUnicode_InsertThousandsGrouping(
9244 PyObject *unicode, Py_ssize_t index,
9245 Py_ssize_t n_buffer,
9246 void *digits, Py_ssize_t n_digits,
9247 Py_ssize_t min_width,
9248 const char *grouping, PyObject *thousands_sep,
9249 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009250{
Victor Stinner41a863c2012-02-24 00:37:51 +01009251 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009252 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009253 Py_ssize_t thousands_sep_len;
9254 Py_ssize_t len;
9255
9256 if (unicode != NULL) {
9257 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009258 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009259 }
9260 else {
9261 kind = PyUnicode_1BYTE_KIND;
9262 data = NULL;
9263 }
9264 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9265 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9266 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9267 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009268 if (thousands_sep_kind < kind) {
9269 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9270 if (!thousands_sep_data)
9271 return -1;
9272 }
9273 else {
9274 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9275 if (!data)
9276 return -1;
9277 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009278 }
9279
Benjamin Petersonead6b532011-12-20 17:23:42 -06009280 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009282 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009283 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009284 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009285 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009286 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009287 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009288 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009289 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009290 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009291 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009292 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009294 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009295 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009296 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009297 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009300 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009301 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009302 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009303 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009304 break;
9305 default:
9306 assert(0);
9307 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009309 if (unicode != NULL && thousands_sep_kind != kind) {
9310 if (thousands_sep_kind < kind)
9311 PyMem_Free(thousands_sep_data);
9312 else
9313 PyMem_Free(data);
9314 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009315 if (unicode == NULL) {
9316 *maxchar = 127;
9317 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009318 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009319 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009320 }
9321 }
9322 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323}
9324
9325
Alexander Belopolsky40018472011-02-26 01:02:56 +00009326Py_ssize_t
9327PyUnicode_Count(PyObject *str,
9328 PyObject *substr,
9329 Py_ssize_t start,
9330 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009332 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009333 PyObject* str_obj;
9334 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009335 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 void *buf1 = NULL, *buf2 = NULL;
9337 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009338
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009339 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009340 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009341 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009342 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009343 if (!sub_obj) {
9344 Py_DECREF(str_obj);
9345 return -1;
9346 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009347 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009348 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009349 Py_DECREF(str_obj);
9350 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351 }
Tim Petersced69f82003-09-16 20:30:58 +00009352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 kind1 = PyUnicode_KIND(str_obj);
9354 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009355 if (kind1 < kind2) {
9356 Py_DECREF(sub_obj);
9357 Py_DECREF(str_obj);
9358 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009359 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009361 len1 = PyUnicode_GET_LENGTH(str_obj);
9362 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009364 if (end - start < len2) {
9365 Py_DECREF(sub_obj);
9366 Py_DECREF(str_obj);
9367 return 0;
9368 }
9369
9370 buf1 = PyUnicode_DATA(str_obj);
9371 buf2 = PyUnicode_DATA(sub_obj);
9372 if (kind2 != kind1) {
9373 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9374 if (!buf2)
9375 goto onError;
9376 }
9377
9378 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009380 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9381 result = asciilib_count(
9382 ((Py_UCS1*)buf1) + start, end - start,
9383 buf2, len2, PY_SSIZE_T_MAX
9384 );
9385 else
9386 result = ucs1lib_count(
9387 ((Py_UCS1*)buf1) + start, end - start,
9388 buf2, len2, PY_SSIZE_T_MAX
9389 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 break;
9391 case PyUnicode_2BYTE_KIND:
9392 result = ucs2lib_count(
9393 ((Py_UCS2*)buf1) + start, end - start,
9394 buf2, len2, PY_SSIZE_T_MAX
9395 );
9396 break;
9397 case PyUnicode_4BYTE_KIND:
9398 result = ucs4lib_count(
9399 ((Py_UCS4*)buf1) + start, end - start,
9400 buf2, len2, PY_SSIZE_T_MAX
9401 );
9402 break;
9403 default:
9404 assert(0); result = 0;
9405 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009406
9407 Py_DECREF(sub_obj);
9408 Py_DECREF(str_obj);
9409
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009410 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 PyMem_Free(buf2);
9412
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 onError:
9415 Py_DECREF(sub_obj);
9416 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009417 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 PyMem_Free(buf2);
9419 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009420}
9421
Alexander Belopolsky40018472011-02-26 01:02:56 +00009422Py_ssize_t
9423PyUnicode_Find(PyObject *str,
9424 PyObject *sub,
9425 Py_ssize_t start,
9426 Py_ssize_t end,
9427 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009429 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009430
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009432 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009433 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009434 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009435 if (!sub) {
9436 Py_DECREF(str);
9437 return -2;
9438 }
9439 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9440 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009441 Py_DECREF(str);
9442 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009443 }
Tim Petersced69f82003-09-16 20:30:58 +00009444
Victor Stinner794d5672011-10-10 03:21:36 +02009445 result = any_find_slice(direction,
9446 str, sub, start, end
9447 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009448
Guido van Rossumd57fd912000-03-10 22:53:23 +00009449 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009450 Py_DECREF(sub);
9451
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452 return result;
9453}
9454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455Py_ssize_t
9456PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9457 Py_ssize_t start, Py_ssize_t end,
9458 int direction)
9459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009461 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 if (PyUnicode_READY(str) == -1)
9463 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009464 if (start < 0 || end < 0) {
9465 PyErr_SetString(PyExc_IndexError, "string index out of range");
9466 return -2;
9467 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 if (end > PyUnicode_GET_LENGTH(str))
9469 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009470 if (start >= end)
9471 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009473 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9474 kind, end-start, ch, direction);
9475 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009477 else
9478 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479}
9480
Alexander Belopolsky40018472011-02-26 01:02:56 +00009481static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009482tailmatch(PyObject *self,
9483 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009484 Py_ssize_t start,
9485 Py_ssize_t end,
9486 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488 int kind_self;
9489 int kind_sub;
9490 void *data_self;
9491 void *data_sub;
9492 Py_ssize_t offset;
9493 Py_ssize_t i;
9494 Py_ssize_t end_sub;
9495
9496 if (PyUnicode_READY(self) == -1 ||
9497 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009498 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009500 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9501 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009503 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009505 if (PyUnicode_GET_LENGTH(substring) == 0)
9506 return 1;
9507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 kind_self = PyUnicode_KIND(self);
9509 data_self = PyUnicode_DATA(self);
9510 kind_sub = PyUnicode_KIND(substring);
9511 data_sub = PyUnicode_DATA(substring);
9512 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9513
9514 if (direction > 0)
9515 offset = end;
9516 else
9517 offset = start;
9518
9519 if (PyUnicode_READ(kind_self, data_self, offset) ==
9520 PyUnicode_READ(kind_sub, data_sub, 0) &&
9521 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9522 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9523 /* If both are of the same kind, memcmp is sufficient */
9524 if (kind_self == kind_sub) {
9525 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009526 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 data_sub,
9528 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009529 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530 }
9531 /* otherwise we have to compare each character by first accesing it */
9532 else {
9533 /* We do not need to compare 0 and len(substring)-1 because
9534 the if statement above ensured already that they are equal
9535 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 for (i = 1; i < end_sub; ++i) {
9537 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9538 PyUnicode_READ(kind_sub, data_sub, i))
9539 return 0;
9540 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009541 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009543 }
9544
9545 return 0;
9546}
9547
Alexander Belopolsky40018472011-02-26 01:02:56 +00009548Py_ssize_t
9549PyUnicode_Tailmatch(PyObject *str,
9550 PyObject *substr,
9551 Py_ssize_t start,
9552 Py_ssize_t end,
9553 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009554{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009555 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009556
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557 str = PyUnicode_FromObject(str);
9558 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560 substr = PyUnicode_FromObject(substr);
9561 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009562 Py_DECREF(str);
9563 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564 }
Tim Petersced69f82003-09-16 20:30:58 +00009565
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009566 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568 Py_DECREF(str);
9569 Py_DECREF(substr);
9570 return result;
9571}
9572
Guido van Rossumd57fd912000-03-10 22:53:23 +00009573/* Apply fixfct filter to the Unicode object self and return a
9574 reference to the modified object */
9575
Alexander Belopolsky40018472011-02-26 01:02:56 +00009576static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009577fixup(PyObject *self,
9578 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 PyObject *u;
9581 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009582 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009584 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009586 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009587 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 /* fix functions return the new maximum character in a string,
9590 if the kind of the resulting unicode object does not change,
9591 everything is fine. Otherwise we need to change the string kind
9592 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009593 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009594
9595 if (maxchar_new == 0) {
9596 /* no changes */;
9597 if (PyUnicode_CheckExact(self)) {
9598 Py_DECREF(u);
9599 Py_INCREF(self);
9600 return self;
9601 }
9602 else
9603 return u;
9604 }
9605
Victor Stinnere6abb482012-05-02 01:15:40 +02009606 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009607
Victor Stinnereaab6042011-12-11 22:22:39 +01009608 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009609 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009610
9611 /* In case the maximum character changed, we need to
9612 convert the string to the new category. */
9613 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9614 if (v == NULL) {
9615 Py_DECREF(u);
9616 return NULL;
9617 }
9618 if (maxchar_new > maxchar_old) {
9619 /* If the maxchar increased so that the kind changed, not all
9620 characters are representable anymore and we need to fix the
9621 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009622 _PyUnicode_FastCopyCharacters(v, 0,
9623 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009624 maxchar_old = fixfct(v);
9625 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626 }
9627 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009628 _PyUnicode_FastCopyCharacters(v, 0,
9629 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009630 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009631 Py_DECREF(u);
9632 assert(_PyUnicode_CheckConsistency(v, 1));
9633 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634}
9635
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009636static PyObject *
9637ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009639 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9640 char *resdata, *data = PyUnicode_DATA(self);
9641 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009642
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 res = PyUnicode_New(len, 127);
9644 if (res == NULL)
9645 return NULL;
9646 resdata = PyUnicode_DATA(res);
9647 if (lower)
9648 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009650 _Py_bytes_upper(resdata, data, len);
9651 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652}
9653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009655handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009657 Py_ssize_t j;
9658 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009659 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009661
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009662 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9663
9664 where ! is a negation and \p{xxx} is a character with property xxx.
9665 */
9666 for (j = i - 1; j >= 0; j--) {
9667 c = PyUnicode_READ(kind, data, j);
9668 if (!_PyUnicode_IsCaseIgnorable(c))
9669 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009671 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9672 if (final_sigma) {
9673 for (j = i + 1; j < length; j++) {
9674 c = PyUnicode_READ(kind, data, j);
9675 if (!_PyUnicode_IsCaseIgnorable(c))
9676 break;
9677 }
9678 final_sigma = j == length || !_PyUnicode_IsCased(c);
9679 }
9680 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009681}
9682
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009683static int
9684lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9685 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687 /* Obscure special case. */
9688 if (c == 0x3A3) {
9689 mapped[0] = handle_capital_sigma(kind, data, length, i);
9690 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009692 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009693}
9694
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695static Py_ssize_t
9696do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009698 Py_ssize_t i, k = 0;
9699 int n_res, j;
9700 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009701
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009702 c = PyUnicode_READ(kind, data, 0);
9703 n_res = _PyUnicode_ToUpperFull(c, mapped);
9704 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009705 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009707 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009708 for (i = 1; i < length; i++) {
9709 c = PyUnicode_READ(kind, data, i);
9710 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9711 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009712 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009713 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009714 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009715 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009716 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009717}
9718
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009719static Py_ssize_t
9720do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9721 Py_ssize_t i, k = 0;
9722
9723 for (i = 0; i < length; i++) {
9724 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9725 int n_res, j;
9726 if (Py_UNICODE_ISUPPER(c)) {
9727 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9728 }
9729 else if (Py_UNICODE_ISLOWER(c)) {
9730 n_res = _PyUnicode_ToUpperFull(c, mapped);
9731 }
9732 else {
9733 n_res = 1;
9734 mapped[0] = c;
9735 }
9736 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009737 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009738 res[k++] = mapped[j];
9739 }
9740 }
9741 return k;
9742}
9743
9744static Py_ssize_t
9745do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9746 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009748 Py_ssize_t i, k = 0;
9749
9750 for (i = 0; i < length; i++) {
9751 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9752 int n_res, j;
9753 if (lower)
9754 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9755 else
9756 n_res = _PyUnicode_ToUpperFull(c, mapped);
9757 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009758 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009759 res[k++] = mapped[j];
9760 }
9761 }
9762 return k;
9763}
9764
9765static Py_ssize_t
9766do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9767{
9768 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9769}
9770
9771static Py_ssize_t
9772do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9773{
9774 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9775}
9776
Benjamin Petersone51757f2012-01-12 21:10:29 -05009777static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009778do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9779{
9780 Py_ssize_t i, k = 0;
9781
9782 for (i = 0; i < length; i++) {
9783 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9784 Py_UCS4 mapped[3];
9785 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9786 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009787 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009788 res[k++] = mapped[j];
9789 }
9790 }
9791 return k;
9792}
9793
9794static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009795do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9796{
9797 Py_ssize_t i, k = 0;
9798 int previous_is_cased;
9799
9800 previous_is_cased = 0;
9801 for (i = 0; i < length; i++) {
9802 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9803 Py_UCS4 mapped[3];
9804 int n_res, j;
9805
9806 if (previous_is_cased)
9807 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9808 else
9809 n_res = _PyUnicode_ToTitleFull(c, mapped);
9810
9811 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009812 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009813 res[k++] = mapped[j];
9814 }
9815
9816 previous_is_cased = _PyUnicode_IsCased(c);
9817 }
9818 return k;
9819}
9820
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009821static PyObject *
9822case_operation(PyObject *self,
9823 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9824{
9825 PyObject *res = NULL;
9826 Py_ssize_t length, newlength = 0;
9827 int kind, outkind;
9828 void *data, *outdata;
9829 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9830
Benjamin Petersoneea48462012-01-16 14:28:50 -05009831 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009832
9833 kind = PyUnicode_KIND(self);
9834 data = PyUnicode_DATA(self);
9835 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009836 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009837 PyErr_SetString(PyExc_OverflowError, "string is too long");
9838 return NULL;
9839 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009840 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009841 if (tmp == NULL)
9842 return PyErr_NoMemory();
9843 newlength = perform(kind, data, length, tmp, &maxchar);
9844 res = PyUnicode_New(newlength, maxchar);
9845 if (res == NULL)
9846 goto leave;
9847 tmpend = tmp + newlength;
9848 outdata = PyUnicode_DATA(res);
9849 outkind = PyUnicode_KIND(res);
9850 switch (outkind) {
9851 case PyUnicode_1BYTE_KIND:
9852 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9853 break;
9854 case PyUnicode_2BYTE_KIND:
9855 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9856 break;
9857 case PyUnicode_4BYTE_KIND:
9858 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9859 break;
9860 default:
9861 assert(0);
9862 break;
9863 }
9864 leave:
9865 PyMem_FREE(tmp);
9866 return res;
9867}
9868
Tim Peters8ce9f162004-08-27 01:49:32 +00009869PyObject *
9870PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009871{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009873 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009875 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009876 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9877 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009878 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009880 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009882 int use_memcpy;
9883 unsigned char *res_data = NULL, *sep_data = NULL;
9884 PyObject *last_obj;
9885 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009887 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009888 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009889 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009890 }
9891
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009892 /* NOTE: the following code can't call back into Python code,
9893 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009894 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009895
Tim Peters05eba1f2004-08-27 21:32:02 +00009896 seqlen = PySequence_Fast_GET_SIZE(fseq);
9897 /* If empty sequence, return u"". */
9898 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009899 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009900 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009901 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009902
Tim Peters05eba1f2004-08-27 21:32:02 +00009903 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009904 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009905 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009906 if (seqlen == 1) {
9907 if (PyUnicode_CheckExact(items[0])) {
9908 res = items[0];
9909 Py_INCREF(res);
9910 Py_DECREF(fseq);
9911 return res;
9912 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009913 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009914 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009915 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009916 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009917 /* Set up sep and seplen */
9918 if (separator == NULL) {
9919 /* fall back to a blank space separator */
9920 sep = PyUnicode_FromOrdinal(' ');
9921 if (!sep)
9922 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009923 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009924 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009925 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009926 else {
9927 if (!PyUnicode_Check(separator)) {
9928 PyErr_Format(PyExc_TypeError,
9929 "separator: expected str instance,"
9930 " %.80s found",
9931 Py_TYPE(separator)->tp_name);
9932 goto onError;
9933 }
9934 if (PyUnicode_READY(separator))
9935 goto onError;
9936 sep = separator;
9937 seplen = PyUnicode_GET_LENGTH(separator);
9938 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9939 /* inc refcount to keep this code path symmetric with the
9940 above case of a blank separator */
9941 Py_INCREF(sep);
9942 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009943 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009944 }
9945
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009946 /* There are at least two things to join, or else we have a subclass
9947 * of str in the sequence.
9948 * Do a pre-pass to figure out the total amount of space we'll
9949 * need (sz), and see whether all argument are strings.
9950 */
9951 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009952#ifdef Py_DEBUG
9953 use_memcpy = 0;
9954#else
9955 use_memcpy = 1;
9956#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009957 for (i = 0; i < seqlen; i++) {
9958 const Py_ssize_t old_sz = sz;
9959 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009960 if (!PyUnicode_Check(item)) {
9961 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009962 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009963 " %.80s found",
9964 i, Py_TYPE(item)->tp_name);
9965 goto onError;
9966 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 if (PyUnicode_READY(item) == -1)
9968 goto onError;
9969 sz += PyUnicode_GET_LENGTH(item);
9970 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009971 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009972 if (i != 0)
9973 sz += seplen;
9974 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9975 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009976 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009977 goto onError;
9978 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009979 if (use_memcpy && last_obj != NULL) {
9980 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9981 use_memcpy = 0;
9982 }
9983 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009984 }
Tim Petersced69f82003-09-16 20:30:58 +00009985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009987 if (res == NULL)
9988 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009989
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009990 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009991#ifdef Py_DEBUG
9992 use_memcpy = 0;
9993#else
9994 if (use_memcpy) {
9995 res_data = PyUnicode_1BYTE_DATA(res);
9996 kind = PyUnicode_KIND(res);
9997 if (seplen != 0)
9998 sep_data = PyUnicode_1BYTE_DATA(sep);
9999 }
10000#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010001 if (use_memcpy) {
10002 for (i = 0; i < seqlen; ++i) {
10003 Py_ssize_t itemlen;
10004 item = items[i];
10005
10006 /* Copy item, and maybe the separator. */
10007 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010008 Py_MEMCPY(res_data,
10009 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010010 kind * seplen);
10011 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010012 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010013
10014 itemlen = PyUnicode_GET_LENGTH(item);
10015 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010016 Py_MEMCPY(res_data,
10017 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010018 kind * itemlen);
10019 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010020 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010021 }
10022 assert(res_data == PyUnicode_1BYTE_DATA(res)
10023 + kind * PyUnicode_GET_LENGTH(res));
10024 }
10025 else {
10026 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10027 Py_ssize_t itemlen;
10028 item = items[i];
10029
10030 /* Copy item, and maybe the separator. */
10031 if (i && seplen != 0) {
10032 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10033 res_offset += seplen;
10034 }
10035
10036 itemlen = PyUnicode_GET_LENGTH(item);
10037 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010038 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010039 res_offset += itemlen;
10040 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010041 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010042 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010043 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010044
Tim Peters05eba1f2004-08-27 21:32:02 +000010045 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010047 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049
Benjamin Peterson29060642009-01-31 22:14:21 +000010050 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +000010051 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010053 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010054 return NULL;
10055}
10056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057#define FILL(kind, data, value, start, length) \
10058 do { \
10059 Py_ssize_t i_ = 0; \
10060 assert(kind != PyUnicode_WCHAR_KIND); \
10061 switch ((kind)) { \
10062 case PyUnicode_1BYTE_KIND: { \
10063 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010064 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 break; \
10066 } \
10067 case PyUnicode_2BYTE_KIND: { \
10068 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10069 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10070 break; \
10071 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010072 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10074 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10075 break; \
10076 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010077 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 } \
10079 } while (0)
10080
Victor Stinnerd3f08822012-05-29 12:57:52 +020010081void
10082_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10083 Py_UCS4 fill_char)
10084{
10085 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10086 const void *data = PyUnicode_DATA(unicode);
10087 assert(PyUnicode_IS_READY(unicode));
10088 assert(unicode_modifiable(unicode));
10089 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10090 assert(start >= 0);
10091 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10092 FILL(kind, data, fill_char, start, length);
10093}
10094
Victor Stinner3fe55312012-01-04 00:33:50 +010010095Py_ssize_t
10096PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10097 Py_UCS4 fill_char)
10098{
10099 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010100
10101 if (!PyUnicode_Check(unicode)) {
10102 PyErr_BadInternalCall();
10103 return -1;
10104 }
10105 if (PyUnicode_READY(unicode) == -1)
10106 return -1;
10107 if (unicode_check_modifiable(unicode))
10108 return -1;
10109
Victor Stinnerd3f08822012-05-29 12:57:52 +020010110 if (start < 0) {
10111 PyErr_SetString(PyExc_IndexError, "string index out of range");
10112 return -1;
10113 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010114 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10115 PyErr_SetString(PyExc_ValueError,
10116 "fill character is bigger than "
10117 "the string maximum character");
10118 return -1;
10119 }
10120
10121 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10122 length = Py_MIN(maxlen, length);
10123 if (length <= 0)
10124 return 0;
10125
Victor Stinnerd3f08822012-05-29 12:57:52 +020010126 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010127 return length;
10128}
10129
Victor Stinner9310abb2011-10-05 00:59:23 +020010130static PyObject *
10131pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010132 Py_ssize_t left,
10133 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 PyObject *u;
10137 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010138 int kind;
10139 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140
10141 if (left < 0)
10142 left = 0;
10143 if (right < 0)
10144 right = 0;
10145
Victor Stinnerc4b49542011-12-11 22:44:26 +010010146 if (left == 0 && right == 0)
10147 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10150 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010151 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10152 return NULL;
10153 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010155 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010157 if (!u)
10158 return NULL;
10159
10160 kind = PyUnicode_KIND(u);
10161 data = PyUnicode_DATA(u);
10162 if (left)
10163 FILL(kind, data, fill, 0, left);
10164 if (right)
10165 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010166 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010167 assert(_PyUnicode_CheckConsistency(u, 1));
10168 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169}
10170
Alexander Belopolsky40018472011-02-26 01:02:56 +000010171PyObject *
10172PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175
10176 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010177 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010178 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010179 if (PyUnicode_READY(string) == -1) {
10180 Py_DECREF(string);
10181 return NULL;
10182 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183
Benjamin Petersonead6b532011-12-20 17:23:42 -060010184 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186 if (PyUnicode_IS_ASCII(string))
10187 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010188 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 PyUnicode_GET_LENGTH(string), keepends);
10190 else
10191 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 break;
10195 case PyUnicode_2BYTE_KIND:
10196 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 PyUnicode_GET_LENGTH(string), keepends);
10199 break;
10200 case PyUnicode_4BYTE_KIND:
10201 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 PyUnicode_GET_LENGTH(string), keepends);
10204 break;
10205 default:
10206 assert(0);
10207 list = 0;
10208 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209 Py_DECREF(string);
10210 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010211}
10212
Alexander Belopolsky40018472011-02-26 01:02:56 +000010213static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010214split(PyObject *self,
10215 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010216 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010217{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010218 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 void *buf1, *buf2;
10220 Py_ssize_t len1, len2;
10221 PyObject* out;
10222
Guido van Rossumd57fd912000-03-10 22:53:23 +000010223 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010224 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010225
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 if (PyUnicode_READY(self) == -1)
10227 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010230 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010232 if (PyUnicode_IS_ASCII(self))
10233 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235 PyUnicode_GET_LENGTH(self), maxcount
10236 );
10237 else
10238 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010239 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010240 PyUnicode_GET_LENGTH(self), maxcount
10241 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 case PyUnicode_2BYTE_KIND:
10243 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010244 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 PyUnicode_GET_LENGTH(self), maxcount
10246 );
10247 case PyUnicode_4BYTE_KIND:
10248 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010249 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 PyUnicode_GET_LENGTH(self), maxcount
10251 );
10252 default:
10253 assert(0);
10254 return NULL;
10255 }
10256
10257 if (PyUnicode_READY(substring) == -1)
10258 return NULL;
10259
10260 kind1 = PyUnicode_KIND(self);
10261 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 len1 = PyUnicode_GET_LENGTH(self);
10263 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010264 if (kind1 < kind2 || len1 < len2) {
10265 out = PyList_New(1);
10266 if (out == NULL)
10267 return NULL;
10268 Py_INCREF(self);
10269 PyList_SET_ITEM(out, 0, self);
10270 return out;
10271 }
10272 buf1 = PyUnicode_DATA(self);
10273 buf2 = PyUnicode_DATA(substring);
10274 if (kind2 != kind1) {
10275 buf2 = _PyUnicode_AsKind(substring, kind1);
10276 if (!buf2)
10277 return NULL;
10278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010280 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010282 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10283 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010284 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010285 else
10286 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010287 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 break;
10289 case PyUnicode_2BYTE_KIND:
10290 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010291 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 break;
10293 case PyUnicode_4BYTE_KIND:
10294 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010295 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 break;
10297 default:
10298 out = NULL;
10299 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010300 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 PyMem_Free(buf2);
10302 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303}
10304
Alexander Belopolsky40018472011-02-26 01:02:56 +000010305static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010306rsplit(PyObject *self,
10307 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010308 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010309{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010310 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 void *buf1, *buf2;
10312 Py_ssize_t len1, len2;
10313 PyObject* out;
10314
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010315 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010316 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 if (PyUnicode_READY(self) == -1)
10319 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010322 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010324 if (PyUnicode_IS_ASCII(self))
10325 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010326 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010327 PyUnicode_GET_LENGTH(self), maxcount
10328 );
10329 else
10330 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010331 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010332 PyUnicode_GET_LENGTH(self), maxcount
10333 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 case PyUnicode_2BYTE_KIND:
10335 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010336 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 PyUnicode_GET_LENGTH(self), maxcount
10338 );
10339 case PyUnicode_4BYTE_KIND:
10340 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010341 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 PyUnicode_GET_LENGTH(self), maxcount
10343 );
10344 default:
10345 assert(0);
10346 return NULL;
10347 }
10348
10349 if (PyUnicode_READY(substring) == -1)
10350 return NULL;
10351
10352 kind1 = PyUnicode_KIND(self);
10353 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 len1 = PyUnicode_GET_LENGTH(self);
10355 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010356 if (kind1 < kind2 || len1 < len2) {
10357 out = PyList_New(1);
10358 if (out == NULL)
10359 return NULL;
10360 Py_INCREF(self);
10361 PyList_SET_ITEM(out, 0, self);
10362 return out;
10363 }
10364 buf1 = PyUnicode_DATA(self);
10365 buf2 = PyUnicode_DATA(substring);
10366 if (kind2 != kind1) {
10367 buf2 = _PyUnicode_AsKind(substring, kind1);
10368 if (!buf2)
10369 return NULL;
10370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010372 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010374 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10375 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010376 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010377 else
10378 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010379 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 break;
10381 case PyUnicode_2BYTE_KIND:
10382 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010383 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 break;
10385 case PyUnicode_4BYTE_KIND:
10386 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010387 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 break;
10389 default:
10390 out = NULL;
10391 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010392 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 PyMem_Free(buf2);
10394 return out;
10395}
10396
10397static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010398anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10399 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010401 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010403 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10404 return asciilib_find(buf1, len1, buf2, len2, offset);
10405 else
10406 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 case PyUnicode_2BYTE_KIND:
10408 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10409 case PyUnicode_4BYTE_KIND:
10410 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10411 }
10412 assert(0);
10413 return -1;
10414}
10415
10416static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010417anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10418 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010420 switch (kind) {
10421 case PyUnicode_1BYTE_KIND:
10422 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10423 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10424 else
10425 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10426 case PyUnicode_2BYTE_KIND:
10427 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10428 case PyUnicode_4BYTE_KIND:
10429 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10430 }
10431 assert(0);
10432 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010433}
10434
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010435static void
10436replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10437 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10438{
10439 int kind = PyUnicode_KIND(u);
10440 void *data = PyUnicode_DATA(u);
10441 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10442 if (kind == PyUnicode_1BYTE_KIND) {
10443 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10444 (Py_UCS1 *)data + len,
10445 u1, u2, maxcount);
10446 }
10447 else if (kind == PyUnicode_2BYTE_KIND) {
10448 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10449 (Py_UCS2 *)data + len,
10450 u1, u2, maxcount);
10451 }
10452 else {
10453 assert(kind == PyUnicode_4BYTE_KIND);
10454 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10455 (Py_UCS4 *)data + len,
10456 u1, u2, maxcount);
10457 }
10458}
10459
Alexander Belopolsky40018472011-02-26 01:02:56 +000010460static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461replace(PyObject *self, PyObject *str1,
10462 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 PyObject *u;
10465 char *sbuf = PyUnicode_DATA(self);
10466 char *buf1 = PyUnicode_DATA(str1);
10467 char *buf2 = PyUnicode_DATA(str2);
10468 int srelease = 0, release1 = 0, release2 = 0;
10469 int skind = PyUnicode_KIND(self);
10470 int kind1 = PyUnicode_KIND(str1);
10471 int kind2 = PyUnicode_KIND(str2);
10472 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10473 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10474 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010475 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010476 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477
10478 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010479 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010481 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482
Victor Stinner59de0ee2011-10-07 10:01:28 +020010483 if (str1 == str2)
10484 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485
Victor Stinner49a0a212011-10-12 23:46:10 +020010486 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010487 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10488 if (maxchar < maxchar_str1)
10489 /* substring too wide to be present */
10490 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010491 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10492 /* Replacing str1 with str2 may cause a maxchar reduction in the
10493 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010494 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010495 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010498 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010500 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010502 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010503 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010504 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010505
Victor Stinner69ed0f42013-04-09 21:48:24 +020010506 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010507 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010508 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010509 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010510 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010512 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010514
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010515 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10516 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010517 }
10518 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 int rkind = skind;
10520 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010521 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 if (kind1 < rkind) {
10524 /* widen substring */
10525 buf1 = _PyUnicode_AsKind(str1, rkind);
10526 if (!buf1) goto error;
10527 release1 = 1;
10528 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010529 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010530 if (i < 0)
10531 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 if (rkind > kind2) {
10533 /* widen replacement */
10534 buf2 = _PyUnicode_AsKind(str2, rkind);
10535 if (!buf2) goto error;
10536 release2 = 1;
10537 }
10538 else if (rkind < kind2) {
10539 /* widen self and buf1 */
10540 rkind = kind2;
10541 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010542 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 sbuf = _PyUnicode_AsKind(self, rkind);
10544 if (!sbuf) goto error;
10545 srelease = 1;
10546 buf1 = _PyUnicode_AsKind(str1, rkind);
10547 if (!buf1) goto error;
10548 release1 = 1;
10549 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010550 u = PyUnicode_New(slen, maxchar);
10551 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010553 assert(PyUnicode_KIND(u) == rkind);
10554 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010555
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010556 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010557 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010562
10563 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010564 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010565 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010566 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010567 if (i == -1)
10568 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010571 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010573 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010574 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010575 }
10576 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010578 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 int rkind = skind;
10580 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010583 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 buf1 = _PyUnicode_AsKind(str1, rkind);
10585 if (!buf1) goto error;
10586 release1 = 1;
10587 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010588 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 if (n == 0)
10590 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010592 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 buf2 = _PyUnicode_AsKind(str2, rkind);
10594 if (!buf2) goto error;
10595 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010598 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 rkind = kind2;
10600 sbuf = _PyUnicode_AsKind(self, rkind);
10601 if (!sbuf) goto error;
10602 srelease = 1;
10603 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010604 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 buf1 = _PyUnicode_AsKind(str1, rkind);
10606 if (!buf1) goto error;
10607 release1 = 1;
10608 }
10609 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10610 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010611 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 PyErr_SetString(PyExc_OverflowError,
10613 "replace string is too long");
10614 goto error;
10615 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010616 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010617 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010618 _Py_INCREF_UNICODE_EMPTY();
10619 if (!unicode_empty)
10620 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010621 u = unicode_empty;
10622 goto done;
10623 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010624 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 PyErr_SetString(PyExc_OverflowError,
10626 "replace string is too long");
10627 goto error;
10628 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010629 u = PyUnicode_New(new_size, maxchar);
10630 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010632 assert(PyUnicode_KIND(u) == rkind);
10633 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 ires = i = 0;
10635 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010636 while (n-- > 0) {
10637 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010638 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010639 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010640 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010641 if (j == -1)
10642 break;
10643 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010644 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010645 memcpy(res + rkind * ires,
10646 sbuf + rkind * i,
10647 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010649 }
10650 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010652 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010654 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010660 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010661 memcpy(res + rkind * ires,
10662 sbuf + rkind * i,
10663 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010664 }
10665 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010666 /* interleave */
10667 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010668 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010670 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010672 if (--n <= 0)
10673 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010674 memcpy(res + rkind * ires,
10675 sbuf + rkind * i,
10676 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 ires++;
10678 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010679 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010680 memcpy(res + rkind * ires,
10681 sbuf + rkind * i,
10682 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010683 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010684 }
10685
10686 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010687 unicode_adjust_maxchar(&u);
10688 if (u == NULL)
10689 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010691
10692 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 if (srelease)
10694 PyMem_FREE(sbuf);
10695 if (release1)
10696 PyMem_FREE(buf1);
10697 if (release2)
10698 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010699 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010701
Benjamin Peterson29060642009-01-31 22:14:21 +000010702 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010704 if (srelease)
10705 PyMem_FREE(sbuf);
10706 if (release1)
10707 PyMem_FREE(buf1);
10708 if (release2)
10709 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010710 return unicode_result_unchanged(self);
10711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010712 error:
10713 if (srelease && sbuf)
10714 PyMem_FREE(sbuf);
10715 if (release1 && buf1)
10716 PyMem_FREE(buf1);
10717 if (release2 && buf2)
10718 PyMem_FREE(buf2);
10719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720}
10721
10722/* --- Unicode Object Methods --------------------------------------------- */
10723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010724PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010725 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726\n\
10727Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010728characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729
10730static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010731unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010733 if (PyUnicode_READY(self) == -1)
10734 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010735 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010736}
10737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010738PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010739 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740\n\
10741Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010742have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743
10744static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010745unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010747 if (PyUnicode_READY(self) == -1)
10748 return NULL;
10749 if (PyUnicode_GET_LENGTH(self) == 0)
10750 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010751 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752}
10753
Benjamin Petersond5890c82012-01-14 13:23:30 -050010754PyDoc_STRVAR(casefold__doc__,
10755 "S.casefold() -> str\n\
10756\n\
10757Return a version of S suitable for caseless comparisons.");
10758
10759static PyObject *
10760unicode_casefold(PyObject *self)
10761{
10762 if (PyUnicode_READY(self) == -1)
10763 return NULL;
10764 if (PyUnicode_IS_ASCII(self))
10765 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010766 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010767}
10768
10769
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010770/* Argument converter. Coerces to a single unicode character */
10771
10772static int
10773convert_uc(PyObject *obj, void *addr)
10774{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010776 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010777
Benjamin Peterson14339b62009-01-31 16:36:08 +000010778 uniobj = PyUnicode_FromObject(obj);
10779 if (uniobj == NULL) {
10780 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010781 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010782 return 0;
10783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010785 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010787 Py_DECREF(uniobj);
10788 return 0;
10789 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010790 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010791 Py_DECREF(uniobj);
10792 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010793}
10794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010795PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010796 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010798Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010799done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800
10801static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010802unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010803{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010804 Py_ssize_t marg, left;
10805 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 Py_UCS4 fillchar = ' ';
10807
Victor Stinnere9a29352011-10-01 02:14:59 +020010808 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810
Benjamin Petersonbac79492012-01-14 13:34:47 -050010811 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812 return NULL;
10813
Victor Stinnerc4b49542011-12-11 22:44:26 +010010814 if (PyUnicode_GET_LENGTH(self) >= width)
10815 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816
Victor Stinnerc4b49542011-12-11 22:44:26 +010010817 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818 left = marg / 2 + (marg & width & 1);
10819
Victor Stinner9310abb2011-10-05 00:59:23 +020010820 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821}
10822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823/* This function assumes that str1 and str2 are readied by the caller. */
10824
Marc-André Lemburge5034372000-08-08 08:04:29 +000010825static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010826unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010827{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010828#define COMPARE(TYPE1, TYPE2) \
10829 do { \
10830 TYPE1* p1 = (TYPE1 *)data1; \
10831 TYPE2* p2 = (TYPE2 *)data2; \
10832 TYPE1* end = p1 + len; \
10833 Py_UCS4 c1, c2; \
10834 for (; p1 != end; p1++, p2++) { \
10835 c1 = *p1; \
10836 c2 = *p2; \
10837 if (c1 != c2) \
10838 return (c1 < c2) ? -1 : 1; \
10839 } \
10840 } \
10841 while (0)
10842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010843 int kind1, kind2;
10844 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010845 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010847 kind1 = PyUnicode_KIND(str1);
10848 kind2 = PyUnicode_KIND(str2);
10849 data1 = PyUnicode_DATA(str1);
10850 data2 = PyUnicode_DATA(str2);
10851 len1 = PyUnicode_GET_LENGTH(str1);
10852 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010853 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010854
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010855 switch(kind1) {
10856 case PyUnicode_1BYTE_KIND:
10857 {
10858 switch(kind2) {
10859 case PyUnicode_1BYTE_KIND:
10860 {
10861 int cmp = memcmp(data1, data2, len);
10862 /* normalize result of memcmp() into the range [-1; 1] */
10863 if (cmp < 0)
10864 return -1;
10865 if (cmp > 0)
10866 return 1;
10867 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010868 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010869 case PyUnicode_2BYTE_KIND:
10870 COMPARE(Py_UCS1, Py_UCS2);
10871 break;
10872 case PyUnicode_4BYTE_KIND:
10873 COMPARE(Py_UCS1, Py_UCS4);
10874 break;
10875 default:
10876 assert(0);
10877 }
10878 break;
10879 }
10880 case PyUnicode_2BYTE_KIND:
10881 {
10882 switch(kind2) {
10883 case PyUnicode_1BYTE_KIND:
10884 COMPARE(Py_UCS2, Py_UCS1);
10885 break;
10886 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010887 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010888 COMPARE(Py_UCS2, Py_UCS2);
10889 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010890 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010891 case PyUnicode_4BYTE_KIND:
10892 COMPARE(Py_UCS2, Py_UCS4);
10893 break;
10894 default:
10895 assert(0);
10896 }
10897 break;
10898 }
10899 case PyUnicode_4BYTE_KIND:
10900 {
10901 switch(kind2) {
10902 case PyUnicode_1BYTE_KIND:
10903 COMPARE(Py_UCS4, Py_UCS1);
10904 break;
10905 case PyUnicode_2BYTE_KIND:
10906 COMPARE(Py_UCS4, Py_UCS2);
10907 break;
10908 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010909 {
10910#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10911 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10912 /* normalize result of wmemcmp() into the range [-1; 1] */
10913 if (cmp < 0)
10914 return -1;
10915 if (cmp > 0)
10916 return 1;
10917#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010918 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010919#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010920 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010921 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010922 default:
10923 assert(0);
10924 }
10925 break;
10926 }
10927 default:
10928 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010929 }
10930
Victor Stinner770e19e2012-10-04 22:59:45 +020010931 if (len1 == len2)
10932 return 0;
10933 if (len1 < len2)
10934 return -1;
10935 else
10936 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010937
10938#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010939}
10940
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010941Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010942unicode_compare_eq(PyObject *str1, PyObject *str2)
10943{
10944 int kind;
10945 void *data1, *data2;
10946 Py_ssize_t len;
10947 int cmp;
10948
Victor Stinnere5567ad2012-10-23 02:48:49 +020010949 len = PyUnicode_GET_LENGTH(str1);
10950 if (PyUnicode_GET_LENGTH(str2) != len)
10951 return 0;
10952 kind = PyUnicode_KIND(str1);
10953 if (PyUnicode_KIND(str2) != kind)
10954 return 0;
10955 data1 = PyUnicode_DATA(str1);
10956 data2 = PyUnicode_DATA(str2);
10957
10958 cmp = memcmp(data1, data2, len * kind);
10959 return (cmp == 0);
10960}
10961
10962
Alexander Belopolsky40018472011-02-26 01:02:56 +000010963int
10964PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010966 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10967 if (PyUnicode_READY(left) == -1 ||
10968 PyUnicode_READY(right) == -1)
10969 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010970
10971 /* a string is equal to itself */
10972 if (left == right)
10973 return 0;
10974
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010975 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010977 PyErr_Format(PyExc_TypeError,
10978 "Can't compare %.100s and %.100s",
10979 left->ob_type->tp_name,
10980 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 return -1;
10982}
10983
Martin v. Löwis5b222132007-06-10 09:51:05 +000010984int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010985_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10986{
10987 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10988 if (right_str == NULL)
10989 return -1;
10990 return PyUnicode_Compare(left, right_str);
10991}
10992
10993int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010994PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 Py_ssize_t i;
10997 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998 Py_UCS4 chr;
10999
Victor Stinner910337b2011-10-03 03:20:16 +020011000 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 if (PyUnicode_READY(uni) == -1)
11002 return -1;
11003 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011004 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011005 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011006 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011007 size_t len, len2 = strlen(str);
11008 int cmp;
11009
11010 len = Py_MIN(len1, len2);
11011 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011012 if (cmp != 0) {
11013 if (cmp < 0)
11014 return -1;
11015 else
11016 return 1;
11017 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011018 if (len1 > len2)
11019 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011020 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011021 return -1; /* str is longer */
11022 return 0;
11023 }
11024 else {
11025 void *data = PyUnicode_DATA(uni);
11026 /* Compare Unicode string and source character set string */
11027 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011028 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011029 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11030 /* This check keeps Python strings that end in '\0' from comparing equal
11031 to C strings identical up to that point. */
11032 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11033 return 1; /* uni is longer */
11034 if (str[i])
11035 return -1; /* str is longer */
11036 return 0;
11037 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011038}
11039
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011040
Benjamin Peterson29060642009-01-31 22:14:21 +000011041#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011042 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011043
Alexander Belopolsky40018472011-02-26 01:02:56 +000011044PyObject *
11045PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011046{
11047 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011048 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011049
Victor Stinnere5567ad2012-10-23 02:48:49 +020011050 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11051 Py_RETURN_NOTIMPLEMENTED;
11052
11053 if (PyUnicode_READY(left) == -1 ||
11054 PyUnicode_READY(right) == -1)
11055 return NULL;
11056
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011057 if (left == right) {
11058 switch (op) {
11059 case Py_EQ:
11060 case Py_LE:
11061 case Py_GE:
11062 /* a string is equal to itself */
11063 v = Py_True;
11064 break;
11065 case Py_NE:
11066 case Py_LT:
11067 case Py_GT:
11068 v = Py_False;
11069 break;
11070 default:
11071 PyErr_BadArgument();
11072 return NULL;
11073 }
11074 }
11075 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011076 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011077 result ^= (op == Py_NE);
11078 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011079 }
11080 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011081 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011082
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011083 /* Convert the return value to a Boolean */
11084 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011085 case Py_LE:
11086 v = TEST_COND(result <= 0);
11087 break;
11088 case Py_GE:
11089 v = TEST_COND(result >= 0);
11090 break;
11091 case Py_LT:
11092 v = TEST_COND(result == -1);
11093 break;
11094 case Py_GT:
11095 v = TEST_COND(result == 1);
11096 break;
11097 default:
11098 PyErr_BadArgument();
11099 return NULL;
11100 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011101 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011102 Py_INCREF(v);
11103 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011104}
11105
Alexander Belopolsky40018472011-02-26 01:02:56 +000011106int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011107_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11108{
11109 return unicode_eq(aa, bb);
11110}
11111
11112int
Alexander Belopolsky40018472011-02-26 01:02:56 +000011113PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011114{
Thomas Wouters477c8d52006-05-27 19:21:47 +000011115 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020011116 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 void *buf1, *buf2;
11118 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011119 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011120
11121 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000011122 sub = PyUnicode_FromObject(element);
11123 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011124 PyErr_Format(PyExc_TypeError,
11125 "'in <string>' requires string as left operand, not %s",
11126 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011127 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011128 }
11129
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011131 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011132 Py_DECREF(sub);
11133 return -1;
11134 }
11135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 kind1 = PyUnicode_KIND(str);
11137 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011138 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050011140 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011141 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 }
11143 len1 = PyUnicode_GET_LENGTH(str);
11144 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011145 if (len1 < len2) {
11146 Py_DECREF(sub);
11147 Py_DECREF(str);
11148 return 0;
11149 }
11150 buf1 = PyUnicode_DATA(str);
11151 buf2 = PyUnicode_DATA(sub);
11152 if (len2 == 1) {
11153 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11154 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11155 Py_DECREF(sub);
11156 Py_DECREF(str);
11157 return result;
11158 }
11159 if (kind2 != kind1) {
11160 buf2 = _PyUnicode_AsKind(sub, kind1);
11161 if (!buf2) {
11162 Py_DECREF(sub);
11163 Py_DECREF(str);
11164 return -1;
11165 }
11166 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167
Victor Stinner77282cb2013-04-14 19:22:47 +020011168 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 case PyUnicode_1BYTE_KIND:
11170 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11171 break;
11172 case PyUnicode_2BYTE_KIND:
11173 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11174 break;
11175 case PyUnicode_4BYTE_KIND:
11176 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11177 break;
11178 default:
11179 result = -1;
11180 assert(0);
11181 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011182
11183 Py_DECREF(str);
11184 Py_DECREF(sub);
11185
Victor Stinner77282cb2013-04-14 19:22:47 +020011186 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011187 PyMem_Free(buf2);
11188
Guido van Rossum403d68b2000-03-13 15:55:09 +000011189 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011190}
11191
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192/* Concat to string or Unicode object giving a new Unicode object. */
11193
Alexander Belopolsky40018472011-02-26 01:02:56 +000011194PyObject *
11195PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011198 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011199 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200
11201 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011207 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
11209 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011210 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011211 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011214 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011215 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011216 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 }
11218
Victor Stinner488fa492011-12-12 00:01:39 +010011219 u_len = PyUnicode_GET_LENGTH(u);
11220 v_len = PyUnicode_GET_LENGTH(v);
11221 if (u_len > PY_SSIZE_T_MAX - v_len) {
11222 PyErr_SetString(PyExc_OverflowError,
11223 "strings are too large to concat");
11224 goto onError;
11225 }
11226 new_len = u_len + v_len;
11227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011229 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011230 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011233 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011235 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011236 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11237 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 Py_DECREF(u);
11239 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011240 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011241 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242
Benjamin Peterson29060642009-01-31 22:14:21 +000011243 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244 Py_XDECREF(u);
11245 Py_XDECREF(v);
11246 return NULL;
11247}
11248
Walter Dörwald1ab83302007-05-18 17:15:44 +000011249void
Victor Stinner23e56682011-10-03 03:54:37 +020011250PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011251{
Victor Stinner23e56682011-10-03 03:54:37 +020011252 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011253 Py_UCS4 maxchar, maxchar2;
11254 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011255
11256 if (p_left == NULL) {
11257 if (!PyErr_Occurred())
11258 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011259 return;
11260 }
Victor Stinner23e56682011-10-03 03:54:37 +020011261 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011262 if (right == NULL || left == NULL
11263 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011264 if (!PyErr_Occurred())
11265 PyErr_BadInternalCall();
11266 goto error;
11267 }
11268
Benjamin Petersonbac79492012-01-14 13:34:47 -050011269 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011270 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011271 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011272 goto error;
11273
Victor Stinner488fa492011-12-12 00:01:39 +010011274 /* Shortcuts */
11275 if (left == unicode_empty) {
11276 Py_DECREF(left);
11277 Py_INCREF(right);
11278 *p_left = right;
11279 return;
11280 }
11281 if (right == unicode_empty)
11282 return;
11283
11284 left_len = PyUnicode_GET_LENGTH(left);
11285 right_len = PyUnicode_GET_LENGTH(right);
11286 if (left_len > PY_SSIZE_T_MAX - right_len) {
11287 PyErr_SetString(PyExc_OverflowError,
11288 "strings are too large to concat");
11289 goto error;
11290 }
11291 new_len = left_len + right_len;
11292
11293 if (unicode_modifiable(left)
11294 && PyUnicode_CheckExact(right)
11295 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011296 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11297 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011298 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011299 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011300 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11301 {
11302 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011303 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011304 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011305
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011306 /* copy 'right' into the newly allocated area of 'left' */
11307 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011308 }
Victor Stinner488fa492011-12-12 00:01:39 +010011309 else {
11310 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11311 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011312 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011313
Victor Stinner488fa492011-12-12 00:01:39 +010011314 /* Concat the two Unicode strings */
11315 res = PyUnicode_New(new_len, maxchar);
11316 if (res == NULL)
11317 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011318 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11319 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011320 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011321 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011322 }
11323 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011324 return;
11325
11326error:
Victor Stinner488fa492011-12-12 00:01:39 +010011327 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011328}
11329
11330void
11331PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11332{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011333 PyUnicode_Append(pleft, right);
11334 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011335}
11336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011337PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011340Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011341string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011342interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
11344static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011345unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011346{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011347 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011348 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011349 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011351 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 void *buf1, *buf2;
11353 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354
Jesus Ceaac451502011-04-20 17:09:23 +020011355 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11356 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011357 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 kind1 = PyUnicode_KIND(self);
11360 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011361 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011362 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011363 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 len1 = PyUnicode_GET_LENGTH(self);
11366 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011368 if (end - start < len2) {
11369 Py_DECREF(substring);
11370 return PyLong_FromLong(0);
11371 }
11372 buf1 = PyUnicode_DATA(self);
11373 buf2 = PyUnicode_DATA(substring);
11374 if (kind2 != kind1) {
11375 buf2 = _PyUnicode_AsKind(substring, kind1);
11376 if (!buf2) {
11377 Py_DECREF(substring);
11378 return NULL;
11379 }
11380 }
11381 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 case PyUnicode_1BYTE_KIND:
11383 iresult = ucs1lib_count(
11384 ((Py_UCS1*)buf1) + start, end - start,
11385 buf2, len2, PY_SSIZE_T_MAX
11386 );
11387 break;
11388 case PyUnicode_2BYTE_KIND:
11389 iresult = ucs2lib_count(
11390 ((Py_UCS2*)buf1) + start, end - start,
11391 buf2, len2, PY_SSIZE_T_MAX
11392 );
11393 break;
11394 case PyUnicode_4BYTE_KIND:
11395 iresult = ucs4lib_count(
11396 ((Py_UCS4*)buf1) + start, end - start,
11397 buf2, len2, PY_SSIZE_T_MAX
11398 );
11399 break;
11400 default:
11401 assert(0); iresult = 0;
11402 }
11403
11404 result = PyLong_FromSsize_t(iresult);
11405
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011406 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011407 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
11409 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011410
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411 return result;
11412}
11413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011414PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011415 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011417Encode S using the codec registered for encoding. Default encoding\n\
11418is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011419handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011420a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11421'xmlcharrefreplace' as well as any other name registered with\n\
11422codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423
11424static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011425unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011427 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428 char *encoding = NULL;
11429 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011430
Benjamin Peterson308d6372009-09-18 21:42:35 +000011431 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11432 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011434 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011435}
11436
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011437PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011438 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439\n\
11440Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011441If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
11443static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011444unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011446 Py_ssize_t i, j, line_pos, src_len, incr;
11447 Py_UCS4 ch;
11448 PyObject *u;
11449 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011450 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011452 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011453 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454
Ezio Melotti745d54d2013-11-16 19:10:57 +020011455 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11456 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458
Antoine Pitrou22425222011-10-04 19:10:51 +020011459 if (PyUnicode_READY(self) == -1)
11460 return NULL;
11461
Thomas Wouters7e474022000-07-16 12:04:32 +000011462 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 src_len = PyUnicode_GET_LENGTH(self);
11464 i = j = line_pos = 0;
11465 kind = PyUnicode_KIND(self);
11466 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011467 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011468 for (; i < src_len; i++) {
11469 ch = PyUnicode_READ(kind, src_data, i);
11470 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011471 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011473 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011475 goto overflow;
11476 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011478 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011482 goto overflow;
11483 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011485 if (ch == '\n' || ch == '\r')
11486 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011488 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011489 if (!found)
11490 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011491
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011493 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494 if (!u)
11495 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011496 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
Antoine Pitroue71d5742011-10-04 15:55:09 +020011498 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499
Antoine Pitroue71d5742011-10-04 15:55:09 +020011500 for (; i < src_len; i++) {
11501 ch = PyUnicode_READ(kind, src_data, i);
11502 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011503 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011504 incr = tabsize - (line_pos % tabsize);
11505 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011506 FILL(kind, dest_data, ' ', j, incr);
11507 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011508 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011509 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011510 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011511 line_pos++;
11512 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011513 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011514 if (ch == '\n' || ch == '\r')
11515 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011517 }
11518 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011519 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011520
Antoine Pitroue71d5742011-10-04 15:55:09 +020011521 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011522 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11523 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524}
11525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011526PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528\n\
11529Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011530such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531arguments start and end are interpreted as in slice notation.\n\
11532\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011533Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534
11535static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011538 /* initialize variables to prevent gcc warning */
11539 PyObject *substring = NULL;
11540 Py_ssize_t start = 0;
11541 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011542 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543
Jesus Ceaac451502011-04-20 17:09:23 +020011544 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11545 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
Christian Heimesd47802e2013-06-29 21:33:36 +020011548 if (PyUnicode_READY(self) == -1) {
11549 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011551 }
11552 if (PyUnicode_READY(substring) == -1) {
11553 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011555 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556
Victor Stinner7931d9a2011-11-04 00:22:48 +010011557 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558
11559 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011561 if (result == -2)
11562 return NULL;
11563
Christian Heimes217cfd12007-12-02 14:31:20 +000011564 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565}
11566
11567static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011568unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011570 void *data;
11571 enum PyUnicode_Kind kind;
11572 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011573
11574 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11575 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011576 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011577 }
11578 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11579 PyErr_SetString(PyExc_IndexError, "string index out of range");
11580 return NULL;
11581 }
11582 kind = PyUnicode_KIND(self);
11583 data = PyUnicode_DATA(self);
11584 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011585 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586}
11587
Guido van Rossumc2504932007-09-18 19:42:40 +000011588/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011589 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011590static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011591unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592{
Guido van Rossumc2504932007-09-18 19:42:40 +000011593 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011594 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011595
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011596#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011597 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011598#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011599 if (_PyUnicode_HASH(self) != -1)
11600 return _PyUnicode_HASH(self);
11601 if (PyUnicode_READY(self) == -1)
11602 return -1;
11603 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011604 /*
11605 We make the hash of the empty string be 0, rather than using
11606 (prefix ^ suffix), since this slightly obfuscates the hash secret
11607 */
11608 if (len == 0) {
11609 _PyUnicode_HASH(self) = 0;
11610 return 0;
11611 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011612 x = _Py_HashBytes(PyUnicode_DATA(self),
11613 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011615 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616}
11617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011618PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011621Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622
11623static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011624unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011626 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011627 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011628 PyObject *substring = NULL;
11629 Py_ssize_t start = 0;
11630 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631
Jesus Ceaac451502011-04-20 17:09:23 +020011632 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11633 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635
Christian Heimesd47a0452013-06-29 21:21:37 +020011636 if (PyUnicode_READY(self) == -1) {
11637 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011639 }
11640 if (PyUnicode_READY(substring) == -1) {
11641 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011643 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644
Victor Stinner7931d9a2011-11-04 00:22:48 +010011645 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646
11647 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 if (result == -2)
11650 return NULL;
11651
Guido van Rossumd57fd912000-03-10 22:53:23 +000011652 if (result < 0) {
11653 PyErr_SetString(PyExc_ValueError, "substring not found");
11654 return NULL;
11655 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011656
Christian Heimes217cfd12007-12-02 14:31:20 +000011657 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011658}
11659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011660PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011663Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665
11666static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011667unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 Py_ssize_t i, length;
11670 int kind;
11671 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672 int cased;
11673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (PyUnicode_READY(self) == -1)
11675 return NULL;
11676 length = PyUnicode_GET_LENGTH(self);
11677 kind = PyUnicode_KIND(self);
11678 data = PyUnicode_DATA(self);
11679
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (length == 1)
11682 return PyBool_FromLong(
11683 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011685 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011688
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 for (i = 0; i < length; i++) {
11691 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011692
Benjamin Peterson29060642009-01-31 22:14:21 +000011693 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11694 return PyBool_FromLong(0);
11695 else if (!cased && Py_UNICODE_ISLOWER(ch))
11696 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011698 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699}
11700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011701PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011704Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011705at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706
11707static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011708unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 Py_ssize_t i, length;
11711 int kind;
11712 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713 int cased;
11714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 if (PyUnicode_READY(self) == -1)
11716 return NULL;
11717 length = PyUnicode_GET_LENGTH(self);
11718 kind = PyUnicode_KIND(self);
11719 data = PyUnicode_DATA(self);
11720
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 1)
11723 return PyBool_FromLong(
11724 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011726 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011727 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011729
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 for (i = 0; i < length; i++) {
11732 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011733
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11735 return PyBool_FromLong(0);
11736 else if (!cased && Py_UNICODE_ISUPPER(ch))
11737 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011739 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740}
11741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011742PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011745Return True if S is a titlecased string and there is at least one\n\
11746character in S, i.e. upper- and titlecase characters may only\n\
11747follow uncased characters and lowercase characters only cased ones.\n\
11748Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749
11750static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011751unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 Py_ssize_t i, length;
11754 int kind;
11755 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756 int cased, previous_is_cased;
11757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 if (PyUnicode_READY(self) == -1)
11759 return NULL;
11760 length = PyUnicode_GET_LENGTH(self);
11761 kind = PyUnicode_KIND(self);
11762 data = PyUnicode_DATA(self);
11763
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 1) {
11766 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11767 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11768 (Py_UNICODE_ISUPPER(ch) != 0));
11769 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011771 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011774
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775 cased = 0;
11776 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 for (i = 0; i < length; i++) {
11778 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011779
Benjamin Peterson29060642009-01-31 22:14:21 +000011780 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11781 if (previous_is_cased)
11782 return PyBool_FromLong(0);
11783 previous_is_cased = 1;
11784 cased = 1;
11785 }
11786 else if (Py_UNICODE_ISLOWER(ch)) {
11787 if (!previous_is_cased)
11788 return PyBool_FromLong(0);
11789 previous_is_cased = 1;
11790 cased = 1;
11791 }
11792 else
11793 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011795 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796}
11797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011798PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011799 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011801Return True if all characters in S are whitespace\n\
11802and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803
11804static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011805unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 Py_ssize_t i, length;
11808 int kind;
11809 void *data;
11810
11811 if (PyUnicode_READY(self) == -1)
11812 return NULL;
11813 length = PyUnicode_GET_LENGTH(self);
11814 kind = PyUnicode_KIND(self);
11815 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 if (length == 1)
11819 return PyBool_FromLong(
11820 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011822 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011824 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 for (i = 0; i < length; i++) {
11827 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011828 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011831 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011832}
11833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011834PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011835 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011836\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011837Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011838and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011839
11840static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011841unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011842{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 Py_ssize_t i, length;
11844 int kind;
11845 void *data;
11846
11847 if (PyUnicode_READY(self) == -1)
11848 return NULL;
11849 length = PyUnicode_GET_LENGTH(self);
11850 kind = PyUnicode_KIND(self);
11851 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011852
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011853 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011854 if (length == 1)
11855 return PyBool_FromLong(
11856 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011857
11858 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 for (i = 0; i < length; i++) {
11863 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011865 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011866 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011867}
11868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011869PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011870 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011871\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011872Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011874
11875static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011876unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011877{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011878 int kind;
11879 void *data;
11880 Py_ssize_t len, i;
11881
11882 if (PyUnicode_READY(self) == -1)
11883 return NULL;
11884
11885 kind = PyUnicode_KIND(self);
11886 data = PyUnicode_DATA(self);
11887 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011888
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011889 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 if (len == 1) {
11891 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11892 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11893 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011894
11895 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 for (i = 0; i < len; i++) {
11900 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011901 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011902 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011903 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011904 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011905}
11906
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011907PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011908 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011910Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011911False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912
11913static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011914unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 Py_ssize_t i, length;
11917 int kind;
11918 void *data;
11919
11920 if (PyUnicode_READY(self) == -1)
11921 return NULL;
11922 length = PyUnicode_GET_LENGTH(self);
11923 kind = PyUnicode_KIND(self);
11924 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011925
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 if (length == 1)
11928 return PyBool_FromLong(
11929 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011931 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011933 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 for (i = 0; i < length; i++) {
11936 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011939 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940}
11941
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011942PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011943 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011945Return True if all characters in S are digits\n\
11946and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947
11948static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011949unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 Py_ssize_t i, length;
11952 int kind;
11953 void *data;
11954
11955 if (PyUnicode_READY(self) == -1)
11956 return NULL;
11957 length = PyUnicode_GET_LENGTH(self);
11958 kind = PyUnicode_KIND(self);
11959 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960
Guido van Rossumd57fd912000-03-10 22:53:23 +000011961 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 if (length == 1) {
11963 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11964 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11965 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011967 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011969 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 for (i = 0; i < length; i++) {
11972 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011973 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011975 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976}
11977
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011978PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011981Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011982False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983
11984static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011985unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 Py_ssize_t i, length;
11988 int kind;
11989 void *data;
11990
11991 if (PyUnicode_READY(self) == -1)
11992 return NULL;
11993 length = PyUnicode_GET_LENGTH(self);
11994 kind = PyUnicode_KIND(self);
11995 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 if (length == 1)
11999 return PyBool_FromLong(
12000 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012002 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012003 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 for (i = 0; i < length; i++) {
12007 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012008 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012010 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012011}
12012
Martin v. Löwis47383402007-08-15 07:32:56 +000012013int
12014PyUnicode_IsIdentifier(PyObject *self)
12015{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 int kind;
12017 void *data;
12018 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012019 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 if (PyUnicode_READY(self) == -1) {
12022 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012023 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 }
12025
12026 /* Special case for empty strings */
12027 if (PyUnicode_GET_LENGTH(self) == 0)
12028 return 0;
12029 kind = PyUnicode_KIND(self);
12030 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012031
12032 /* PEP 3131 says that the first character must be in
12033 XID_Start and subsequent characters in XID_Continue,
12034 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012035 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012036 letters, digits, underscore). However, given the current
12037 definition of XID_Start and XID_Continue, it is sufficient
12038 to check just for these, except that _ must be allowed
12039 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012041 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012042 return 0;
12043
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012044 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012047 return 1;
12048}
12049
12050PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012051 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012052\n\
12053Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012054to the language definition.\n\
12055\n\
12056Use keyword.iskeyword() to test for reserved identifiers\n\
12057such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012058
12059static PyObject*
12060unicode_isidentifier(PyObject *self)
12061{
12062 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12063}
12064
Georg Brandl559e5d72008-06-11 18:37:52 +000012065PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012066 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012067\n\
12068Return True if all characters in S are considered\n\
12069printable in repr() or S is empty, False otherwise.");
12070
12071static PyObject*
12072unicode_isprintable(PyObject *self)
12073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 Py_ssize_t i, length;
12075 int kind;
12076 void *data;
12077
12078 if (PyUnicode_READY(self) == -1)
12079 return NULL;
12080 length = PyUnicode_GET_LENGTH(self);
12081 kind = PyUnicode_KIND(self);
12082 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012083
12084 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 if (length == 1)
12086 return PyBool_FromLong(
12087 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 for (i = 0; i < length; i++) {
12090 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012091 Py_RETURN_FALSE;
12092 }
12093 }
12094 Py_RETURN_TRUE;
12095}
12096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012097PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012098 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099\n\
12100Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012101iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
12103static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012104unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012106 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107}
12108
Martin v. Löwis18e16552006-02-15 17:27:45 +000012109static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012110unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 if (PyUnicode_READY(self) == -1)
12113 return -1;
12114 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115}
12116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012117PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012118 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012120Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012121done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122
12123static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012124unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012126 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 Py_UCS4 fillchar = ' ';
12128
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012129 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130 return NULL;
12131
Benjamin Petersonbac79492012-01-14 13:34:47 -050012132 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012133 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134
Victor Stinnerc4b49542011-12-11 22:44:26 +010012135 if (PyUnicode_GET_LENGTH(self) >= width)
12136 return unicode_result_unchanged(self);
12137
12138 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139}
12140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012141PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012142 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012144Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
12146static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012147unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012149 if (PyUnicode_READY(self) == -1)
12150 return NULL;
12151 if (PyUnicode_IS_ASCII(self))
12152 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012153 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154}
12155
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012156#define LEFTSTRIP 0
12157#define RIGHTSTRIP 1
12158#define BOTHSTRIP 2
12159
12160/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012161static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012162
12163#define STRIPNAME(i) (stripformat[i]+3)
12164
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012165/* externally visible for str.strip(unicode) */
12166PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012167_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012168{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 void *data;
12170 int kind;
12171 Py_ssize_t i, j, len;
12172 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012173 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12176 return NULL;
12177
12178 kind = PyUnicode_KIND(self);
12179 data = PyUnicode_DATA(self);
12180 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012181 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12183 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012184 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012185
Benjamin Peterson14339b62009-01-31 16:36:08 +000012186 i = 0;
12187 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012188 while (i < len) {
12189 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12190 if (!BLOOM(sepmask, ch))
12191 break;
12192 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12193 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012194 i++;
12195 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012196 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012197
Benjamin Peterson14339b62009-01-31 16:36:08 +000012198 j = len;
12199 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012200 j--;
12201 while (j >= i) {
12202 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12203 if (!BLOOM(sepmask, ch))
12204 break;
12205 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12206 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012207 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012208 }
12209
Benjamin Peterson29060642009-01-31 22:14:21 +000012210 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012211 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012212
Victor Stinner7931d9a2011-11-04 00:22:48 +010012213 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214}
12215
12216PyObject*
12217PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12218{
12219 unsigned char *data;
12220 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012221 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222
Victor Stinnerde636f32011-10-01 03:55:54 +020012223 if (PyUnicode_READY(self) == -1)
12224 return NULL;
12225
Victor Stinner684d5fd2012-05-03 02:32:34 +020012226 length = PyUnicode_GET_LENGTH(self);
12227 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012228
Victor Stinner684d5fd2012-05-03 02:32:34 +020012229 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012230 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231
Victor Stinnerde636f32011-10-01 03:55:54 +020012232 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012233 PyErr_SetString(PyExc_IndexError, "string index out of range");
12234 return NULL;
12235 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012236 if (start >= length || end < start)
12237 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012238
Victor Stinner684d5fd2012-05-03 02:32:34 +020012239 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012240 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012241 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012242 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012243 }
12244 else {
12245 kind = PyUnicode_KIND(self);
12246 data = PyUnicode_1BYTE_DATA(self);
12247 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012248 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012249 length);
12250 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252
12253static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012254do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 Py_ssize_t len, i, j;
12257
12258 if (PyUnicode_READY(self) == -1)
12259 return NULL;
12260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012262
Victor Stinnercc7af722013-04-09 22:39:24 +020012263 if (PyUnicode_IS_ASCII(self)) {
12264 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12265
12266 i = 0;
12267 if (striptype != RIGHTSTRIP) {
12268 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012269 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012270 if (!_Py_ascii_whitespace[ch])
12271 break;
12272 i++;
12273 }
12274 }
12275
12276 j = len;
12277 if (striptype != LEFTSTRIP) {
12278 j--;
12279 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012280 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012281 if (!_Py_ascii_whitespace[ch])
12282 break;
12283 j--;
12284 }
12285 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012286 }
12287 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012288 else {
12289 int kind = PyUnicode_KIND(self);
12290 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012291
Victor Stinnercc7af722013-04-09 22:39:24 +020012292 i = 0;
12293 if (striptype != RIGHTSTRIP) {
12294 while (i < len) {
12295 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12296 if (!Py_UNICODE_ISSPACE(ch))
12297 break;
12298 i++;
12299 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012300 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012301
12302 j = len;
12303 if (striptype != LEFTSTRIP) {
12304 j--;
12305 while (j >= i) {
12306 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12307 if (!Py_UNICODE_ISSPACE(ch))
12308 break;
12309 j--;
12310 }
12311 j++;
12312 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012313 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012314
Victor Stinner7931d9a2011-11-04 00:22:48 +010012315 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316}
12317
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012318
12319static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012320do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012321{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012323
Serhiy Storchakac6792272013-10-19 21:03:34 +030012324 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012325 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012326
Benjamin Peterson14339b62009-01-31 16:36:08 +000012327 if (sep != NULL && sep != Py_None) {
12328 if (PyUnicode_Check(sep))
12329 return _PyUnicode_XStrip(self, striptype, sep);
12330 else {
12331 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012332 "%s arg must be None or str",
12333 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012334 return NULL;
12335 }
12336 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012337
Benjamin Peterson14339b62009-01-31 16:36:08 +000012338 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012339}
12340
12341
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012342PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012343 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012344\n\
12345Return a copy of the string S with leading and trailing\n\
12346whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012347If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012348
12349static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012350unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012351{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012352 if (PyTuple_GET_SIZE(args) == 0)
12353 return do_strip(self, BOTHSTRIP); /* Common case */
12354 else
12355 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012356}
12357
12358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012359PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012360 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012361\n\
12362Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012363If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012364
12365static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012366unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012367{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012368 if (PyTuple_GET_SIZE(args) == 0)
12369 return do_strip(self, LEFTSTRIP); /* Common case */
12370 else
12371 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012372}
12373
12374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012375PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012377\n\
12378Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012379If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012380
12381static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012382unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012383{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012384 if (PyTuple_GET_SIZE(args) == 0)
12385 return do_strip(self, RIGHTSTRIP); /* Common case */
12386 else
12387 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012388}
12389
12390
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012392unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012394 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012396
Serhiy Storchaka05997252013-01-26 12:14:02 +020012397 if (len < 1)
12398 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012399
Victor Stinnerc4b49542011-12-11 22:44:26 +010012400 /* no repeat, return original string */
12401 if (len == 1)
12402 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012403
Benjamin Petersonbac79492012-01-14 13:34:47 -050012404 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 return NULL;
12406
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012407 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012408 PyErr_SetString(PyExc_OverflowError,
12409 "repeated string is too long");
12410 return NULL;
12411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012413
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012414 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012415 if (!u)
12416 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012417 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 if (PyUnicode_GET_LENGTH(str) == 1) {
12420 const int kind = PyUnicode_KIND(str);
12421 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012422 if (kind == PyUnicode_1BYTE_KIND) {
12423 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012424 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012425 }
12426 else if (kind == PyUnicode_2BYTE_KIND) {
12427 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012428 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012429 ucs2[n] = fill_char;
12430 } else {
12431 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12432 assert(kind == PyUnicode_4BYTE_KIND);
12433 for (n = 0; n < len; ++n)
12434 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012435 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 }
12437 else {
12438 /* number of characters copied this far */
12439 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012440 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 char *to = (char *) PyUnicode_DATA(u);
12442 Py_MEMCPY(to, PyUnicode_DATA(str),
12443 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012444 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 n = (done <= nchars-done) ? done : nchars-done;
12446 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012448 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012449 }
12450
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012451 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012452 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453}
12454
Alexander Belopolsky40018472011-02-26 01:02:56 +000012455PyObject *
12456PyUnicode_Replace(PyObject *obj,
12457 PyObject *subobj,
12458 PyObject *replobj,
12459 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460{
12461 PyObject *self;
12462 PyObject *str1;
12463 PyObject *str2;
12464 PyObject *result;
12465
12466 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012467 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012468 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012470 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012471 Py_DECREF(self);
12472 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473 }
12474 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012475 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012476 Py_DECREF(self);
12477 Py_DECREF(str1);
12478 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012480 if (PyUnicode_READY(self) == -1 ||
12481 PyUnicode_READY(str1) == -1 ||
12482 PyUnicode_READY(str2) == -1)
12483 result = NULL;
12484 else
12485 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486 Py_DECREF(self);
12487 Py_DECREF(str1);
12488 Py_DECREF(str2);
12489 return result;
12490}
12491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012492PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012493 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494\n\
12495Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012496old replaced by new. If the optional argument count is\n\
12497given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498
12499static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 PyObject *str1;
12503 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012504 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505 PyObject *result;
12506
Martin v. Löwis18e16552006-02-15 17:27:45 +000012507 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012509 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012510 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012512 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 return NULL;
12514 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012515 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012516 Py_DECREF(str1);
12517 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012518 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012519 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12520 result = NULL;
12521 else
12522 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
12524 Py_DECREF(str1);
12525 Py_DECREF(str2);
12526 return result;
12527}
12528
Alexander Belopolsky40018472011-02-26 01:02:56 +000012529static PyObject *
12530unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012532 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533 Py_ssize_t isize;
12534 Py_ssize_t osize, squote, dquote, i, o;
12535 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012536 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012538
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012540 return NULL;
12541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 isize = PyUnicode_GET_LENGTH(unicode);
12543 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012545 /* Compute length of output, quote characters, and
12546 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012547 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 max = 127;
12549 squote = dquote = 0;
12550 ikind = PyUnicode_KIND(unicode);
12551 for (i = 0; i < isize; i++) {
12552 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012553 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012555 case '\'': squote++; break;
12556 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012558 incr = 2;
12559 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 default:
12561 /* Fast-path ASCII */
12562 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012563 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012565 ;
12566 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012569 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012571 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012573 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012575 if (osize > PY_SSIZE_T_MAX - incr) {
12576 PyErr_SetString(PyExc_OverflowError,
12577 "string is too long to generate repr");
12578 return NULL;
12579 }
12580 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 }
12582
12583 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012584 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012586 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 if (dquote)
12588 /* Both squote and dquote present. Use squote,
12589 and escape them */
12590 osize += squote;
12591 else
12592 quote = '"';
12593 }
Victor Stinner55c08782013-04-14 18:45:39 +020012594 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595
12596 repr = PyUnicode_New(osize, max);
12597 if (repr == NULL)
12598 return NULL;
12599 okind = PyUnicode_KIND(repr);
12600 odata = PyUnicode_DATA(repr);
12601
12602 PyUnicode_WRITE(okind, odata, 0, quote);
12603 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012604 if (unchanged) {
12605 _PyUnicode_FastCopyCharacters(repr, 1,
12606 unicode, 0,
12607 isize);
12608 }
12609 else {
12610 for (i = 0, o = 1; i < isize; i++) {
12611 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612
Victor Stinner55c08782013-04-14 18:45:39 +020012613 /* Escape quotes and backslashes */
12614 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012615 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012617 continue;
12618 }
12619
12620 /* Map special whitespace to '\t', \n', '\r' */
12621 if (ch == '\t') {
12622 PyUnicode_WRITE(okind, odata, o++, '\\');
12623 PyUnicode_WRITE(okind, odata, o++, 't');
12624 }
12625 else if (ch == '\n') {
12626 PyUnicode_WRITE(okind, odata, o++, '\\');
12627 PyUnicode_WRITE(okind, odata, o++, 'n');
12628 }
12629 else if (ch == '\r') {
12630 PyUnicode_WRITE(okind, odata, o++, '\\');
12631 PyUnicode_WRITE(okind, odata, o++, 'r');
12632 }
12633
12634 /* Map non-printable US ASCII to '\xhh' */
12635 else if (ch < ' ' || ch == 0x7F) {
12636 PyUnicode_WRITE(okind, odata, o++, '\\');
12637 PyUnicode_WRITE(okind, odata, o++, 'x');
12638 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12639 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12640 }
12641
12642 /* Copy ASCII characters as-is */
12643 else if (ch < 0x7F) {
12644 PyUnicode_WRITE(okind, odata, o++, ch);
12645 }
12646
12647 /* Non-ASCII characters */
12648 else {
12649 /* Map Unicode whitespace and control characters
12650 (categories Z* and C* except ASCII space)
12651 */
12652 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12653 PyUnicode_WRITE(okind, odata, o++, '\\');
12654 /* Map 8-bit characters to '\xhh' */
12655 if (ch <= 0xff) {
12656 PyUnicode_WRITE(okind, odata, o++, 'x');
12657 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12658 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12659 }
12660 /* Map 16-bit characters to '\uxxxx' */
12661 else if (ch <= 0xffff) {
12662 PyUnicode_WRITE(okind, odata, o++, 'u');
12663 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12664 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12665 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12666 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12667 }
12668 /* Map 21-bit characters to '\U00xxxxxx' */
12669 else {
12670 PyUnicode_WRITE(okind, odata, o++, 'U');
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12674 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12675 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12677 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12679 }
12680 }
12681 /* Copy characters as-is */
12682 else {
12683 PyUnicode_WRITE(okind, odata, o++, ch);
12684 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012685 }
12686 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012689 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012690 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691}
12692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012693PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012694 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695\n\
12696Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012697such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698arguments start and end are interpreted as in slice notation.\n\
12699\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012700Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701
12702static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012705 /* initialize variables to prevent gcc warning */
12706 PyObject *substring = NULL;
12707 Py_ssize_t start = 0;
12708 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012709 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710
Jesus Ceaac451502011-04-20 17:09:23 +020012711 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12712 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012713 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714
Christian Heimesea71a522013-06-29 21:17:34 +020012715 if (PyUnicode_READY(self) == -1) {
12716 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012718 }
12719 if (PyUnicode_READY(substring) == -1) {
12720 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723
Victor Stinner7931d9a2011-11-04 00:22:48 +010012724 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725
12726 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012728 if (result == -2)
12729 return NULL;
12730
Christian Heimes217cfd12007-12-02 14:31:20 +000012731 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732}
12733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012734PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012735 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012737Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012738
12739static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012742 /* initialize variables to prevent gcc warning */
12743 PyObject *substring = NULL;
12744 Py_ssize_t start = 0;
12745 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747
Jesus Ceaac451502011-04-20 17:09:23 +020012748 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12749 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012750 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751
Christian Heimesea71a522013-06-29 21:17:34 +020012752 if (PyUnicode_READY(self) == -1) {
12753 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012755 }
12756 if (PyUnicode_READY(substring) == -1) {
12757 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012759 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760
Victor Stinner7931d9a2011-11-04 00:22:48 +010012761 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012762
12763 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765 if (result == -2)
12766 return NULL;
12767
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768 if (result < 0) {
12769 PyErr_SetString(PyExc_ValueError, "substring not found");
12770 return NULL;
12771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772
Christian Heimes217cfd12007-12-02 14:31:20 +000012773 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774}
12775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012776PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012779Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012780done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781
12782static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012783unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012785 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012786 Py_UCS4 fillchar = ' ';
12787
Victor Stinnere9a29352011-10-01 02:14:59 +020012788 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012789 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012790
Benjamin Petersonbac79492012-01-14 13:34:47 -050012791 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792 return NULL;
12793
Victor Stinnerc4b49542011-12-11 22:44:26 +010012794 if (PyUnicode_GET_LENGTH(self) >= width)
12795 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796
Victor Stinnerc4b49542011-12-11 22:44:26 +010012797 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798}
12799
Alexander Belopolsky40018472011-02-26 01:02:56 +000012800PyObject *
12801PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802{
12803 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012804
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805 s = PyUnicode_FromObject(s);
12806 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012807 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 if (sep != NULL) {
12809 sep = PyUnicode_FromObject(sep);
12810 if (sep == NULL) {
12811 Py_DECREF(s);
12812 return NULL;
12813 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814 }
12815
Victor Stinner9310abb2011-10-05 00:59:23 +020012816 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817
12818 Py_DECREF(s);
12819 Py_XDECREF(sep);
12820 return result;
12821}
12822
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012823PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012824 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825\n\
12826Return a list of the words in S, using sep as the\n\
12827delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012828splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012829whitespace string is a separator and empty strings are\n\
12830removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831
12832static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012833unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012835 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012836 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012837 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012839 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12840 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841 return NULL;
12842
12843 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012844 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012846 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012848 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849}
12850
Thomas Wouters477c8d52006-05-27 19:21:47 +000012851PyObject *
12852PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12853{
12854 PyObject* str_obj;
12855 PyObject* sep_obj;
12856 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012857 int kind1, kind2;
12858 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012860
12861 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012862 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012863 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012864 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012865 if (!sep_obj) {
12866 Py_DECREF(str_obj);
12867 return NULL;
12868 }
12869 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12870 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012871 Py_DECREF(str_obj);
12872 return NULL;
12873 }
12874
Victor Stinner14f8f022011-10-05 20:58:25 +020012875 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012876 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 len1 = PyUnicode_GET_LENGTH(str_obj);
12878 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012879 if (kind1 < kind2 || len1 < len2) {
12880 _Py_INCREF_UNICODE_EMPTY();
12881 if (!unicode_empty)
12882 out = NULL;
12883 else {
12884 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12885 Py_DECREF(unicode_empty);
12886 }
12887 Py_DECREF(sep_obj);
12888 Py_DECREF(str_obj);
12889 return out;
12890 }
12891 buf1 = PyUnicode_DATA(str_obj);
12892 buf2 = PyUnicode_DATA(sep_obj);
12893 if (kind2 != kind1) {
12894 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12895 if (!buf2)
12896 goto onError;
12897 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012899 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012901 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12902 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12903 else
12904 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905 break;
12906 case PyUnicode_2BYTE_KIND:
12907 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12908 break;
12909 case PyUnicode_4BYTE_KIND:
12910 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12911 break;
12912 default:
12913 assert(0);
12914 out = 0;
12915 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012916
12917 Py_DECREF(sep_obj);
12918 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012919 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012920 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012921
12922 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 onError:
12924 Py_DECREF(sep_obj);
12925 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012926 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012927 PyMem_Free(buf2);
12928 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012929}
12930
12931
12932PyObject *
12933PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12934{
12935 PyObject* str_obj;
12936 PyObject* sep_obj;
12937 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012938 int kind1, kind2;
12939 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012941
12942 str_obj = PyUnicode_FromObject(str_in);
12943 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012944 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012945 sep_obj = PyUnicode_FromObject(sep_in);
12946 if (!sep_obj) {
12947 Py_DECREF(str_obj);
12948 return NULL;
12949 }
12950
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012951 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012952 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012953 len1 = PyUnicode_GET_LENGTH(str_obj);
12954 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012955 if (kind1 < kind2 || len1 < len2) {
12956 _Py_INCREF_UNICODE_EMPTY();
12957 if (!unicode_empty)
12958 out = NULL;
12959 else {
12960 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12961 Py_DECREF(unicode_empty);
12962 }
12963 Py_DECREF(sep_obj);
12964 Py_DECREF(str_obj);
12965 return out;
12966 }
12967 buf1 = PyUnicode_DATA(str_obj);
12968 buf2 = PyUnicode_DATA(sep_obj);
12969 if (kind2 != kind1) {
12970 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12971 if (!buf2)
12972 goto onError;
12973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012975 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012976 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012977 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12978 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12979 else
12980 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981 break;
12982 case PyUnicode_2BYTE_KIND:
12983 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12984 break;
12985 case PyUnicode_4BYTE_KIND:
12986 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12987 break;
12988 default:
12989 assert(0);
12990 out = 0;
12991 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012992
12993 Py_DECREF(sep_obj);
12994 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012995 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012997
12998 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012999 onError:
13000 Py_DECREF(sep_obj);
13001 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013002 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 PyMem_Free(buf2);
13004 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013005}
13006
13007PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013008 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013009\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013010Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013011the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013012found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013013
13014static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013015unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013016{
Victor Stinner9310abb2011-10-05 00:59:23 +020013017 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013018}
13019
13020PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000013021 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013022\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013023Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013024the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013025separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013026
13027static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013028unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013029{
Victor Stinner9310abb2011-10-05 00:59:23 +020013030 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013031}
13032
Alexander Belopolsky40018472011-02-26 01:02:56 +000013033PyObject *
13034PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013035{
13036 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013037
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013038 s = PyUnicode_FromObject(s);
13039 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013040 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000013041 if (sep != NULL) {
13042 sep = PyUnicode_FromObject(sep);
13043 if (sep == NULL) {
13044 Py_DECREF(s);
13045 return NULL;
13046 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013047 }
13048
Victor Stinner9310abb2011-10-05 00:59:23 +020013049 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013050
13051 Py_DECREF(s);
13052 Py_XDECREF(sep);
13053 return result;
13054}
13055
13056PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013057 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013058\n\
13059Return a list of the words in S, using sep as the\n\
13060delimiter string, starting at the end of the string and\n\
13061working to the front. If maxsplit is given, at most maxsplit\n\
13062splits are done. If sep is not specified, any whitespace string\n\
13063is a separator.");
13064
13065static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013066unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013067{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013068 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013069 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013070 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013071
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013072 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13073 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013074 return NULL;
13075
13076 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013077 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013078 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013079 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013080 else
Victor Stinner9310abb2011-10-05 00:59:23 +020013081 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013082}
13083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013084PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013085 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013086\n\
13087Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013088Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013089is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090
13091static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013092unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013094 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013095 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013097 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13098 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099 return NULL;
13100
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013101 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102}
13103
13104static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013105PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013107 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108}
13109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013110PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112\n\
13113Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013114and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115
13116static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013117unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013118{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013119 if (PyUnicode_READY(self) == -1)
13120 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013121 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122}
13123
Larry Hastings61272b72014-01-07 12:41:53 -080013124/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013125
Larry Hastings31826802013-10-19 00:09:25 -070013126@staticmethod
13127str.maketrans as unicode_maketrans
13128
13129 x: object
13130
13131 y: unicode=NULL
13132
13133 z: unicode=NULL
13134
13135 /
13136
13137Return a translation table usable for str.translate().
13138
13139If there is only one argument, it must be a dictionary mapping Unicode
13140ordinals (integers) or characters to Unicode ordinals, strings or None.
13141Character keys will be then converted to ordinals.
13142If there are two arguments, they must be strings of equal length, and
13143in the resulting dictionary, each character in x will be mapped to the
13144character at the same position in y. If there is a third argument, it
13145must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013146[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013147
Larry Hastings31826802013-10-19 00:09:25 -070013148static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013149unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013150/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013151{
Georg Brandlceee0772007-11-27 23:48:05 +000013152 PyObject *new = NULL, *key, *value;
13153 Py_ssize_t i = 0;
13154 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013155
Georg Brandlceee0772007-11-27 23:48:05 +000013156 new = PyDict_New();
13157 if (!new)
13158 return NULL;
13159 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160 int x_kind, y_kind, z_kind;
13161 void *x_data, *y_data, *z_data;
13162
Georg Brandlceee0772007-11-27 23:48:05 +000013163 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013164 if (!PyUnicode_Check(x)) {
13165 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13166 "be a string if there is a second argument");
13167 goto err;
13168 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013169 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013170 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13171 "arguments must have equal length");
13172 goto err;
13173 }
13174 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013175 x_kind = PyUnicode_KIND(x);
13176 y_kind = PyUnicode_KIND(y);
13177 x_data = PyUnicode_DATA(x);
13178 y_data = PyUnicode_DATA(y);
13179 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13180 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013181 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013182 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013183 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013184 if (!value) {
13185 Py_DECREF(key);
13186 goto err;
13187 }
Georg Brandlceee0772007-11-27 23:48:05 +000013188 res = PyDict_SetItem(new, key, value);
13189 Py_DECREF(key);
13190 Py_DECREF(value);
13191 if (res < 0)
13192 goto err;
13193 }
13194 /* create entries for deleting chars in z */
13195 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013196 z_kind = PyUnicode_KIND(z);
13197 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013198 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013199 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013200 if (!key)
13201 goto err;
13202 res = PyDict_SetItem(new, key, Py_None);
13203 Py_DECREF(key);
13204 if (res < 0)
13205 goto err;
13206 }
13207 }
13208 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 int kind;
13210 void *data;
13211
Georg Brandlceee0772007-11-27 23:48:05 +000013212 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013213 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013214 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13215 "to maketrans it must be a dict");
13216 goto err;
13217 }
13218 /* copy entries into the new dict, converting string keys to int keys */
13219 while (PyDict_Next(x, &i, &key, &value)) {
13220 if (PyUnicode_Check(key)) {
13221 /* convert string keys to integer keys */
13222 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013223 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013224 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13225 "table must be of length 1");
13226 goto err;
13227 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013228 kind = PyUnicode_KIND(key);
13229 data = PyUnicode_DATA(key);
13230 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013231 if (!newkey)
13232 goto err;
13233 res = PyDict_SetItem(new, newkey, value);
13234 Py_DECREF(newkey);
13235 if (res < 0)
13236 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013237 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013238 /* just keep integer keys */
13239 if (PyDict_SetItem(new, key, value) < 0)
13240 goto err;
13241 } else {
13242 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13243 "be strings or integers");
13244 goto err;
13245 }
13246 }
13247 }
13248 return new;
13249 err:
13250 Py_DECREF(new);
13251 return NULL;
13252}
13253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013254PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013257Return a copy of the string S in which each character has been mapped\n\
13258through the given translation table. The table must implement\n\
13259lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13260mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13261this operation raises LookupError, the character is left untouched.\n\
13262Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013263
13264static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013265unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013267 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268}
13269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013270PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013273Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274
13275static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013276unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013278 if (PyUnicode_READY(self) == -1)
13279 return NULL;
13280 if (PyUnicode_IS_ASCII(self))
13281 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013282 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013283}
13284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013285PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013286 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013288Pad a numeric string S with zeros on the left, to fill a field\n\
13289of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290
13291static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013292unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013294 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013295 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013296 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013297 int kind;
13298 void *data;
13299 Py_UCS4 chr;
13300
Martin v. Löwis18e16552006-02-15 17:27:45 +000013301 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302 return NULL;
13303
Benjamin Petersonbac79492012-01-14 13:34:47 -050013304 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013305 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306
Victor Stinnerc4b49542011-12-11 22:44:26 +010013307 if (PyUnicode_GET_LENGTH(self) >= width)
13308 return unicode_result_unchanged(self);
13309
13310 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013311
13312 u = pad(self, fill, 0, '0');
13313
Walter Dörwald068325e2002-04-15 13:36:47 +000013314 if (u == NULL)
13315 return NULL;
13316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 kind = PyUnicode_KIND(u);
13318 data = PyUnicode_DATA(u);
13319 chr = PyUnicode_READ(kind, data, fill);
13320
13321 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013322 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013323 PyUnicode_WRITE(kind, data, 0, chr);
13324 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013325 }
13326
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013327 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013328 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013329}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013330
13331#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013332static PyObject *
13333unicode__decimal2ascii(PyObject *self)
13334{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013335 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013336}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337#endif
13338
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013339PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013342Return True if S starts with the specified prefix, False otherwise.\n\
13343With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013344With optional end, stop comparing S at that position.\n\
13345prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346
13347static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013348unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013349 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013350{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013351 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013352 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013353 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013354 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013355 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356
Jesus Ceaac451502011-04-20 17:09:23 +020013357 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013358 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013359 if (PyTuple_Check(subobj)) {
13360 Py_ssize_t i;
13361 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013362 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013363 if (substring == NULL)
13364 return NULL;
13365 result = tailmatch(self, substring, start, end, -1);
13366 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013367 if (result == -1)
13368 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013369 if (result) {
13370 Py_RETURN_TRUE;
13371 }
13372 }
13373 /* nothing matched */
13374 Py_RETURN_FALSE;
13375 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013376 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013377 if (substring == NULL) {
13378 if (PyErr_ExceptionMatches(PyExc_TypeError))
13379 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13380 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013382 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013383 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013384 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013385 if (result == -1)
13386 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013387 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388}
13389
13390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013391PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013393\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013394Return True if S ends with the specified suffix, False otherwise.\n\
13395With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013396With optional end, stop comparing S at that position.\n\
13397suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013398
13399static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013400unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013401 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013403 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013404 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013405 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013406 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013407 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013408
Jesus Ceaac451502011-04-20 17:09:23 +020013409 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013410 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013411 if (PyTuple_Check(subobj)) {
13412 Py_ssize_t i;
13413 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013414 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013416 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013418 result = tailmatch(self, substring, start, end, +1);
13419 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013420 if (result == -1)
13421 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013422 if (result) {
13423 Py_RETURN_TRUE;
13424 }
13425 }
13426 Py_RETURN_FALSE;
13427 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013428 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013429 if (substring == NULL) {
13430 if (PyErr_ExceptionMatches(PyExc_TypeError))
13431 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13432 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013434 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013435 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013436 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013437 if (result == -1)
13438 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013439 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013440}
13441
Victor Stinner202fdca2012-05-07 12:47:02 +020013442Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013443_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013444{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013445 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13446 writer->data = PyUnicode_DATA(writer->buffer);
13447
13448 if (!writer->readonly) {
13449 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013450 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013451 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013452 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013453 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13454 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13455 writer->kind = PyUnicode_WCHAR_KIND;
13456 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13457
Victor Stinner8f674cc2013-04-17 23:02:17 +020013458 /* Copy-on-write mode: set buffer size to 0 so
13459 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13460 * next write. */
13461 writer->size = 0;
13462 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013463}
13464
Victor Stinnerd3f08822012-05-29 12:57:52 +020013465void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013466_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013467{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013468 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013469
13470 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013471 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013472
13473 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13474 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13475 writer->kind = PyUnicode_WCHAR_KIND;
13476 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013477}
13478
Victor Stinnerd3f08822012-05-29 12:57:52 +020013479int
13480_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13481 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013482{
13483 Py_ssize_t newlen;
13484 PyObject *newbuffer;
13485
Victor Stinnerca9381e2015-09-22 00:58:32 +020013486 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013487 assert((maxchar > writer->maxchar && length >= 0)
13488 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013489
Victor Stinner202fdca2012-05-07 12:47:02 +020013490 if (length > PY_SSIZE_T_MAX - writer->pos) {
13491 PyErr_NoMemory();
13492 return -1;
13493 }
13494 newlen = writer->pos + length;
13495
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013496 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013497
Victor Stinnerd3f08822012-05-29 12:57:52 +020013498 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013499 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013500 if (writer->overallocate
13501 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13502 /* overallocate to limit the number of realloc() */
13503 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013504 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013505 if (newlen < writer->min_length)
13506 newlen = writer->min_length;
13507
Victor Stinnerd3f08822012-05-29 12:57:52 +020013508 writer->buffer = PyUnicode_New(newlen, maxchar);
13509 if (writer->buffer == NULL)
13510 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013511 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013512 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013513 if (writer->overallocate
13514 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13515 /* overallocate to limit the number of realloc() */
13516 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013518 if (newlen < writer->min_length)
13519 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013520
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013521 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013522 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013523 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013524 newbuffer = PyUnicode_New(newlen, maxchar);
13525 if (newbuffer == NULL)
13526 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013527 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13528 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013529 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013530 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013531 }
13532 else {
13533 newbuffer = resize_compact(writer->buffer, newlen);
13534 if (newbuffer == NULL)
13535 return -1;
13536 }
13537 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013538 }
13539 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013540 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013541 newbuffer = PyUnicode_New(writer->size, maxchar);
13542 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013543 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13545 writer->buffer, 0, writer->pos);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020013546 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013547 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013548 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013549 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013550
13551#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013552}
13553
Victor Stinnerca9381e2015-09-22 00:58:32 +020013554int
13555_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13556 enum PyUnicode_Kind kind)
13557{
13558 Py_UCS4 maxchar;
13559
13560 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13561 assert(writer->kind < kind);
13562
13563 switch (kind)
13564 {
13565 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13566 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13567 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13568 default:
13569 assert(0 && "invalid kind");
13570 return -1;
13571 }
13572
13573 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13574}
13575
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013576Py_LOCAL_INLINE(int)
13577_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013578{
13579 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13580 return -1;
13581 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13582 writer->pos++;
13583 return 0;
13584}
13585
13586int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013587_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13588{
13589 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13590}
13591
13592int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013593_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13594{
13595 Py_UCS4 maxchar;
13596 Py_ssize_t len;
13597
13598 if (PyUnicode_READY(str) == -1)
13599 return -1;
13600 len = PyUnicode_GET_LENGTH(str);
13601 if (len == 0)
13602 return 0;
13603 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13604 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013605 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013606 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013607 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013608 Py_INCREF(str);
13609 writer->buffer = str;
13610 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013611 writer->pos += len;
13612 return 0;
13613 }
13614 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13615 return -1;
13616 }
13617 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13618 str, 0, len);
13619 writer->pos += len;
13620 return 0;
13621}
13622
Victor Stinnere215d962012-10-06 23:03:36 +020013623int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013624_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13625 Py_ssize_t start, Py_ssize_t end)
13626{
13627 Py_UCS4 maxchar;
13628 Py_ssize_t len;
13629
13630 if (PyUnicode_READY(str) == -1)
13631 return -1;
13632
13633 assert(0 <= start);
13634 assert(end <= PyUnicode_GET_LENGTH(str));
13635 assert(start <= end);
13636
13637 if (end == 0)
13638 return 0;
13639
13640 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13641 return _PyUnicodeWriter_WriteStr(writer, str);
13642
13643 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13644 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13645 else
13646 maxchar = writer->maxchar;
13647 len = end - start;
13648
13649 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13650 return -1;
13651
13652 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13653 str, start, len);
13654 writer->pos += len;
13655 return 0;
13656}
13657
13658int
Victor Stinner4a587072013-11-19 12:54:53 +010013659_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13660 const char *ascii, Py_ssize_t len)
13661{
13662 if (len == -1)
13663 len = strlen(ascii);
13664
13665 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13666
13667 if (writer->buffer == NULL && !writer->overallocate) {
13668 PyObject *str;
13669
13670 str = _PyUnicode_FromASCII(ascii, len);
13671 if (str == NULL)
13672 return -1;
13673
13674 writer->readonly = 1;
13675 writer->buffer = str;
13676 _PyUnicodeWriter_Update(writer);
13677 writer->pos += len;
13678 return 0;
13679 }
13680
13681 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13682 return -1;
13683
13684 switch (writer->kind)
13685 {
13686 case PyUnicode_1BYTE_KIND:
13687 {
13688 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13689 Py_UCS1 *data = writer->data;
13690
13691 Py_MEMCPY(data + writer->pos, str, len);
13692 break;
13693 }
13694 case PyUnicode_2BYTE_KIND:
13695 {
13696 _PyUnicode_CONVERT_BYTES(
13697 Py_UCS1, Py_UCS2,
13698 ascii, ascii + len,
13699 (Py_UCS2 *)writer->data + writer->pos);
13700 break;
13701 }
13702 case PyUnicode_4BYTE_KIND:
13703 {
13704 _PyUnicode_CONVERT_BYTES(
13705 Py_UCS1, Py_UCS4,
13706 ascii, ascii + len,
13707 (Py_UCS4 *)writer->data + writer->pos);
13708 break;
13709 }
13710 default:
13711 assert(0);
13712 }
13713
13714 writer->pos += len;
13715 return 0;
13716}
13717
13718int
13719_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13720 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013721{
13722 Py_UCS4 maxchar;
13723
13724 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13725 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13726 return -1;
13727 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13728 writer->pos += len;
13729 return 0;
13730}
13731
Victor Stinnerd3f08822012-05-29 12:57:52 +020013732PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013733_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013734{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013735 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013736 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013737 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013738 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013739 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013740 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013741 str = writer->buffer;
13742 writer->buffer = NULL;
13743 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13744 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013745 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013746 if (writer->pos == 0) {
13747 Py_CLEAR(writer->buffer);
13748
13749 /* Get the empty Unicode string singleton ('') */
13750 _Py_INCREF_UNICODE_EMPTY();
13751 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013752 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013753 else {
13754 str = writer->buffer;
13755 writer->buffer = NULL;
13756
13757 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13758 PyObject *str2;
13759 str2 = resize_compact(str, writer->pos);
13760 if (str2 == NULL)
13761 return NULL;
13762 str = str2;
13763 }
13764 }
13765
Victor Stinner15a0bd32013-07-08 22:29:55 +020013766 assert(_PyUnicode_CheckConsistency(str, 1));
13767 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013768}
13769
Victor Stinnerd3f08822012-05-29 12:57:52 +020013770void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013771_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013772{
13773 Py_CLEAR(writer->buffer);
13774}
13775
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013776#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013777
13778PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013779 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013780\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013781Return a formatted version of S, using substitutions from args and kwargs.\n\
13782The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013783
Eric Smith27bbca62010-11-04 17:06:58 +000013784PyDoc_STRVAR(format_map__doc__,
13785 "S.format_map(mapping) -> str\n\
13786\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013787Return a formatted version of S, using substitutions from mapping.\n\
13788The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013789
Eric Smith4a7d76d2008-05-30 18:10:19 +000013790static PyObject *
13791unicode__format__(PyObject* self, PyObject* args)
13792{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013793 PyObject *format_spec;
13794 _PyUnicodeWriter writer;
13795 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013796
13797 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13798 return NULL;
13799
Victor Stinnerd3f08822012-05-29 12:57:52 +020013800 if (PyUnicode_READY(self) == -1)
13801 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013802 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013803 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13804 self, format_spec, 0,
13805 PyUnicode_GET_LENGTH(format_spec));
13806 if (ret == -1) {
13807 _PyUnicodeWriter_Dealloc(&writer);
13808 return NULL;
13809 }
13810 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013811}
13812
Eric Smith8c663262007-08-25 02:26:07 +000013813PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013814 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013815\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013816Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013817
13818static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013819unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013820{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013821 Py_ssize_t size;
13822
13823 /* If it's a compact object, account for base structure +
13824 character data. */
13825 if (PyUnicode_IS_COMPACT_ASCII(v))
13826 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13827 else if (PyUnicode_IS_COMPACT(v))
13828 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013829 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013830 else {
13831 /* If it is a two-block object, account for base object, and
13832 for character block if present. */
13833 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013834 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013835 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013836 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013837 }
13838 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013839 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013840 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013841 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013842 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013843 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013844
13845 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013846}
13847
13848PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013849 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013850
13851static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013852unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013853{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013854 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013855 if (!copy)
13856 return NULL;
13857 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013858}
13859
Guido van Rossumd57fd912000-03-10 22:53:23 +000013860static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013861 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013862 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013863 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13864 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013865 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13866 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013867 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013868 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13869 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13870 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013871 {"expandtabs", (PyCFunction) unicode_expandtabs,
13872 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013873 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013874 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013875 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13876 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13877 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013878 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013879 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13880 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13881 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013882 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013883 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013884 {"splitlines", (PyCFunction) unicode_splitlines,
13885 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013886 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013887 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13888 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13889 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13890 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13891 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13892 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13893 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13894 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13895 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13896 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13897 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13898 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13899 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13900 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013901 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013902 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013903 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013904 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013905 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013906 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013907 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013908 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013909#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013910 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013911 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013912#endif
13913
Benjamin Peterson14339b62009-01-31 16:36:08 +000013914 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013915 {NULL, NULL}
13916};
13917
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013918static PyObject *
13919unicode_mod(PyObject *v, PyObject *w)
13920{
Brian Curtindfc80e32011-08-10 20:28:54 -050013921 if (!PyUnicode_Check(v))
13922 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013923 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013924}
13925
13926static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013927 0, /*nb_add*/
13928 0, /*nb_subtract*/
13929 0, /*nb_multiply*/
13930 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013931};
13932
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013934 (lenfunc) unicode_length, /* sq_length */
13935 PyUnicode_Concat, /* sq_concat */
13936 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13937 (ssizeargfunc) unicode_getitem, /* sq_item */
13938 0, /* sq_slice */
13939 0, /* sq_ass_item */
13940 0, /* sq_ass_slice */
13941 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013942};
13943
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013944static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013945unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013946{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013947 if (PyUnicode_READY(self) == -1)
13948 return NULL;
13949
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013950 if (PyIndex_Check(item)) {
13951 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013952 if (i == -1 && PyErr_Occurred())
13953 return NULL;
13954 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013955 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013956 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013957 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013958 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013959 PyObject *result;
13960 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013961 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013962 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013964 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013965 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013966 return NULL;
13967 }
13968
13969 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013970 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013971 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013972 slicelength == PyUnicode_GET_LENGTH(self)) {
13973 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013974 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013975 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013976 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013977 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013978 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013979 src_kind = PyUnicode_KIND(self);
13980 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013981 if (!PyUnicode_IS_ASCII(self)) {
13982 kind_limit = kind_maxchar_limit(src_kind);
13983 max_char = 0;
13984 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13985 ch = PyUnicode_READ(src_kind, src_data, cur);
13986 if (ch > max_char) {
13987 max_char = ch;
13988 if (max_char >= kind_limit)
13989 break;
13990 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013991 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013992 }
Victor Stinner55c99112011-10-13 01:17:06 +020013993 else
13994 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013995 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013996 if (result == NULL)
13997 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013998 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013999 dest_data = PyUnicode_DATA(result);
14000
14001 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014002 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14003 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014004 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014005 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014006 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014007 } else {
14008 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14009 return NULL;
14010 }
14011}
14012
14013static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014014 (lenfunc)unicode_length, /* mp_length */
14015 (binaryfunc)unicode_subscript, /* mp_subscript */
14016 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014017};
14018
Guido van Rossumd57fd912000-03-10 22:53:23 +000014019
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020/* Helpers for PyUnicode_Format() */
14021
Victor Stinnera47082312012-10-04 02:19:54 +020014022struct unicode_formatter_t {
14023 PyObject *args;
14024 int args_owned;
14025 Py_ssize_t arglen, argidx;
14026 PyObject *dict;
14027
14028 enum PyUnicode_Kind fmtkind;
14029 Py_ssize_t fmtcnt, fmtpos;
14030 void *fmtdata;
14031 PyObject *fmtstr;
14032
14033 _PyUnicodeWriter writer;
14034};
14035
14036struct unicode_format_arg_t {
14037 Py_UCS4 ch;
14038 int flags;
14039 Py_ssize_t width;
14040 int prec;
14041 int sign;
14042};
14043
Guido van Rossumd57fd912000-03-10 22:53:23 +000014044static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014045unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014046{
Victor Stinnera47082312012-10-04 02:19:54 +020014047 Py_ssize_t argidx = ctx->argidx;
14048
14049 if (argidx < ctx->arglen) {
14050 ctx->argidx++;
14051 if (ctx->arglen < 0)
14052 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014053 else
Victor Stinnera47082312012-10-04 02:19:54 +020014054 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014055 }
14056 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014057 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014058 return NULL;
14059}
14060
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014061/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014062
Victor Stinnera47082312012-10-04 02:19:54 +020014063/* Format a float into the writer if the writer is not NULL, or into *p_output
14064 otherwise.
14065
14066 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014067static int
Victor Stinnera47082312012-10-04 02:19:54 +020014068formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14069 PyObject **p_output,
14070 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014071{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014072 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014073 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014074 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014075 int prec;
14076 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014077
Guido van Rossumd57fd912000-03-10 22:53:23 +000014078 x = PyFloat_AsDouble(v);
14079 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014080 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014081
Victor Stinnera47082312012-10-04 02:19:54 +020014082 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014083 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014084 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014085
Victor Stinnera47082312012-10-04 02:19:54 +020014086 if (arg->flags & F_ALT)
14087 dtoa_flags = Py_DTSF_ALT;
14088 else
14089 dtoa_flags = 0;
14090 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014091 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014092 return -1;
14093 len = strlen(p);
14094 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014095 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014096 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014097 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014098 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014099 }
14100 else
14101 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014102 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014103 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014104}
14105
Victor Stinnerd0880d52012-04-27 23:40:13 +020014106/* formatlong() emulates the format codes d, u, o, x and X, and
14107 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14108 * Python's regular ints.
14109 * Return value: a new PyUnicodeObject*, or NULL if error.
14110 * The output string is of the form
14111 * "-"? ("0x" | "0X")? digit+
14112 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14113 * set in flags. The case of hex digits will be correct,
14114 * There will be at least prec digits, zero-filled on the left if
14115 * necessary to get that many.
14116 * val object to be converted
14117 * flags bitmask of format flags; only F_ALT is looked at
14118 * prec minimum number of digits; 0-fill on left if needed
14119 * type a character in [duoxX]; u acts the same as d
14120 *
14121 * CAUTION: o, x and X conversions on regular ints can never
14122 * produce a '-' sign, but can for Python's unbounded ints.
14123 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014124PyObject *
14125_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014126{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014127 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014128 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014129 Py_ssize_t i;
14130 int sign; /* 1 if '-', else 0 */
14131 int len; /* number of characters */
14132 Py_ssize_t llen;
14133 int numdigits; /* len == numnondigits + numdigits */
14134 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014135
Victor Stinnerd0880d52012-04-27 23:40:13 +020014136 /* Avoid exceeding SSIZE_T_MAX */
14137 if (prec > INT_MAX-3) {
14138 PyErr_SetString(PyExc_OverflowError,
14139 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014140 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014141 }
14142
14143 assert(PyLong_Check(val));
14144
14145 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014146 default:
14147 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014148 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014149 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014150 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014151 /* int and int subclasses should print numerically when a numeric */
14152 /* format code is used (see issue18780) */
14153 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014154 break;
14155 case 'o':
14156 numnondigits = 2;
14157 result = PyNumber_ToBase(val, 8);
14158 break;
14159 case 'x':
14160 case 'X':
14161 numnondigits = 2;
14162 result = PyNumber_ToBase(val, 16);
14163 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014164 }
14165 if (!result)
14166 return NULL;
14167
14168 assert(unicode_modifiable(result));
14169 assert(PyUnicode_IS_READY(result));
14170 assert(PyUnicode_IS_ASCII(result));
14171
14172 /* To modify the string in-place, there can only be one reference. */
14173 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014174 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014175 PyErr_BadInternalCall();
14176 return NULL;
14177 }
14178 buf = PyUnicode_DATA(result);
14179 llen = PyUnicode_GET_LENGTH(result);
14180 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014181 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014182 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014183 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014184 return NULL;
14185 }
14186 len = (int)llen;
14187 sign = buf[0] == '-';
14188 numnondigits += sign;
14189 numdigits = len - numnondigits;
14190 assert(numdigits > 0);
14191
14192 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014193 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014194 (type == 'o' || type == 'x' || type == 'X'))) {
14195 assert(buf[sign] == '0');
14196 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14197 buf[sign+1] == 'o');
14198 numnondigits -= 2;
14199 buf += 2;
14200 len -= 2;
14201 if (sign)
14202 buf[0] = '-';
14203 assert(len == numnondigits + numdigits);
14204 assert(numdigits > 0);
14205 }
14206
14207 /* Fill with leading zeroes to meet minimum width. */
14208 if (prec > numdigits) {
14209 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14210 numnondigits + prec);
14211 char *b1;
14212 if (!r1) {
14213 Py_DECREF(result);
14214 return NULL;
14215 }
14216 b1 = PyBytes_AS_STRING(r1);
14217 for (i = 0; i < numnondigits; ++i)
14218 *b1++ = *buf++;
14219 for (i = 0; i < prec - numdigits; i++)
14220 *b1++ = '0';
14221 for (i = 0; i < numdigits; i++)
14222 *b1++ = *buf++;
14223 *b1 = '\0';
14224 Py_DECREF(result);
14225 result = r1;
14226 buf = PyBytes_AS_STRING(result);
14227 len = numnondigits + prec;
14228 }
14229
14230 /* Fix up case for hex conversions. */
14231 if (type == 'X') {
14232 /* Need to convert all lower case letters to upper case.
14233 and need to convert 0x to 0X (and -0x to -0X). */
14234 for (i = 0; i < len; i++)
14235 if (buf[i] >= 'a' && buf[i] <= 'x')
14236 buf[i] -= 'a'-'A';
14237 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014238 if (!PyUnicode_Check(result)
14239 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014240 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014241 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014242 Py_DECREF(result);
14243 result = unicode;
14244 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014245 else if (len != PyUnicode_GET_LENGTH(result)) {
14246 if (PyUnicode_Resize(&result, len) < 0)
14247 Py_CLEAR(result);
14248 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014249 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014250}
14251
Ethan Furmandf3ed242014-01-05 06:50:30 -080014252/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014253 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014254 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014255 * -1 and raise an exception on error */
14256static int
Victor Stinnera47082312012-10-04 02:19:54 +020014257mainformatlong(PyObject *v,
14258 struct unicode_format_arg_t *arg,
14259 PyObject **p_output,
14260 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014261{
14262 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014263 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014264
14265 if (!PyNumber_Check(v))
14266 goto wrongtype;
14267
Ethan Furman9ab74802014-03-21 06:38:46 -070014268 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014269 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014270 if (type == 'o' || type == 'x' || type == 'X') {
14271 iobj = PyNumber_Index(v);
14272 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014273 if (PyErr_ExceptionMatches(PyExc_TypeError))
14274 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014275 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014276 }
14277 }
14278 else {
14279 iobj = PyNumber_Long(v);
14280 if (iobj == NULL ) {
14281 if (PyErr_ExceptionMatches(PyExc_TypeError))
14282 goto wrongtype;
14283 return -1;
14284 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014285 }
14286 assert(PyLong_Check(iobj));
14287 }
14288 else {
14289 iobj = v;
14290 Py_INCREF(iobj);
14291 }
14292
14293 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014294 && arg->width == -1 && arg->prec == -1
14295 && !(arg->flags & (F_SIGN | F_BLANK))
14296 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014297 {
14298 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014299 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014300 int base;
14301
Victor Stinnera47082312012-10-04 02:19:54 +020014302 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014303 {
14304 default:
14305 assert(0 && "'type' not in [diuoxX]");
14306 case 'd':
14307 case 'i':
14308 case 'u':
14309 base = 10;
14310 break;
14311 case 'o':
14312 base = 8;
14313 break;
14314 case 'x':
14315 case 'X':
14316 base = 16;
14317 break;
14318 }
14319
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014320 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14321 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014322 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014323 }
14324 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014325 return 1;
14326 }
14327
Ethan Furmanb95b5612015-01-23 20:05:18 -080014328 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014329 Py_DECREF(iobj);
14330 if (res == NULL)
14331 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014332 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014333 return 0;
14334
14335wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014336 switch(type)
14337 {
14338 case 'o':
14339 case 'x':
14340 case 'X':
14341 PyErr_Format(PyExc_TypeError,
14342 "%%%c format: an integer is required, "
14343 "not %.200s",
14344 type, Py_TYPE(v)->tp_name);
14345 break;
14346 default:
14347 PyErr_Format(PyExc_TypeError,
14348 "%%%c format: a number is required, "
14349 "not %.200s",
14350 type, Py_TYPE(v)->tp_name);
14351 break;
14352 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014353 return -1;
14354}
14355
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014356static Py_UCS4
14357formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014358{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014359 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014360 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014361 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014362 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014363 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014364 goto onError;
14365 }
14366 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014367 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014368 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014369 /* make sure number is a type of integer */
14370 if (!PyLong_Check(v)) {
14371 iobj = PyNumber_Index(v);
14372 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014373 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014374 }
14375 v = iobj;
14376 Py_DECREF(iobj);
14377 }
14378 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014379 x = PyLong_AsLong(v);
14380 if (x == -1 && PyErr_Occurred())
14381 goto onError;
14382
Victor Stinner8faf8212011-12-08 22:14:11 +010014383 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014384 PyErr_SetString(PyExc_OverflowError,
14385 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014386 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014387 }
14388
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014389 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014391
Benjamin Peterson29060642009-01-31 22:14:21 +000014392 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014393 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014394 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014395 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014396}
14397
Victor Stinnera47082312012-10-04 02:19:54 +020014398/* Parse options of an argument: flags, width, precision.
14399 Handle also "%(name)" syntax.
14400
14401 Return 0 if the argument has been formatted into arg->str.
14402 Return 1 if the argument has been written into ctx->writer,
14403 Raise an exception and return -1 on error. */
14404static int
14405unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14406 struct unicode_format_arg_t *arg)
14407{
14408#define FORMAT_READ(ctx) \
14409 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14410
14411 PyObject *v;
14412
Victor Stinnera47082312012-10-04 02:19:54 +020014413 if (arg->ch == '(') {
14414 /* Get argument value from a dictionary. Example: "%(name)s". */
14415 Py_ssize_t keystart;
14416 Py_ssize_t keylen;
14417 PyObject *key;
14418 int pcount = 1;
14419
14420 if (ctx->dict == NULL) {
14421 PyErr_SetString(PyExc_TypeError,
14422 "format requires a mapping");
14423 return -1;
14424 }
14425 ++ctx->fmtpos;
14426 --ctx->fmtcnt;
14427 keystart = ctx->fmtpos;
14428 /* Skip over balanced parentheses */
14429 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14430 arg->ch = FORMAT_READ(ctx);
14431 if (arg->ch == ')')
14432 --pcount;
14433 else if (arg->ch == '(')
14434 ++pcount;
14435 ctx->fmtpos++;
14436 }
14437 keylen = ctx->fmtpos - keystart - 1;
14438 if (ctx->fmtcnt < 0 || pcount > 0) {
14439 PyErr_SetString(PyExc_ValueError,
14440 "incomplete format key");
14441 return -1;
14442 }
14443 key = PyUnicode_Substring(ctx->fmtstr,
14444 keystart, keystart + keylen);
14445 if (key == NULL)
14446 return -1;
14447 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014448 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014449 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014450 }
14451 ctx->args = PyObject_GetItem(ctx->dict, key);
14452 Py_DECREF(key);
14453 if (ctx->args == NULL)
14454 return -1;
14455 ctx->args_owned = 1;
14456 ctx->arglen = -1;
14457 ctx->argidx = -2;
14458 }
14459
14460 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014461 while (--ctx->fmtcnt >= 0) {
14462 arg->ch = FORMAT_READ(ctx);
14463 ctx->fmtpos++;
14464 switch (arg->ch) {
14465 case '-': arg->flags |= F_LJUST; continue;
14466 case '+': arg->flags |= F_SIGN; continue;
14467 case ' ': arg->flags |= F_BLANK; continue;
14468 case '#': arg->flags |= F_ALT; continue;
14469 case '0': arg->flags |= F_ZERO; continue;
14470 }
14471 break;
14472 }
14473
14474 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014475 if (arg->ch == '*') {
14476 v = unicode_format_getnextarg(ctx);
14477 if (v == NULL)
14478 return -1;
14479 if (!PyLong_Check(v)) {
14480 PyErr_SetString(PyExc_TypeError,
14481 "* wants int");
14482 return -1;
14483 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014484 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014485 if (arg->width == -1 && PyErr_Occurred())
14486 return -1;
14487 if (arg->width < 0) {
14488 arg->flags |= F_LJUST;
14489 arg->width = -arg->width;
14490 }
14491 if (--ctx->fmtcnt >= 0) {
14492 arg->ch = FORMAT_READ(ctx);
14493 ctx->fmtpos++;
14494 }
14495 }
14496 else if (arg->ch >= '0' && arg->ch <= '9') {
14497 arg->width = arg->ch - '0';
14498 while (--ctx->fmtcnt >= 0) {
14499 arg->ch = FORMAT_READ(ctx);
14500 ctx->fmtpos++;
14501 if (arg->ch < '0' || arg->ch > '9')
14502 break;
14503 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14504 mixing signed and unsigned comparison. Since arg->ch is between
14505 '0' and '9', casting to int is safe. */
14506 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14507 PyErr_SetString(PyExc_ValueError,
14508 "width too big");
14509 return -1;
14510 }
14511 arg->width = arg->width*10 + (arg->ch - '0');
14512 }
14513 }
14514
14515 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014516 if (arg->ch == '.') {
14517 arg->prec = 0;
14518 if (--ctx->fmtcnt >= 0) {
14519 arg->ch = FORMAT_READ(ctx);
14520 ctx->fmtpos++;
14521 }
14522 if (arg->ch == '*') {
14523 v = unicode_format_getnextarg(ctx);
14524 if (v == NULL)
14525 return -1;
14526 if (!PyLong_Check(v)) {
14527 PyErr_SetString(PyExc_TypeError,
14528 "* wants int");
14529 return -1;
14530 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014531 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014532 if (arg->prec == -1 && PyErr_Occurred())
14533 return -1;
14534 if (arg->prec < 0)
14535 arg->prec = 0;
14536 if (--ctx->fmtcnt >= 0) {
14537 arg->ch = FORMAT_READ(ctx);
14538 ctx->fmtpos++;
14539 }
14540 }
14541 else if (arg->ch >= '0' && arg->ch <= '9') {
14542 arg->prec = arg->ch - '0';
14543 while (--ctx->fmtcnt >= 0) {
14544 arg->ch = FORMAT_READ(ctx);
14545 ctx->fmtpos++;
14546 if (arg->ch < '0' || arg->ch > '9')
14547 break;
14548 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14549 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014550 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014551 return -1;
14552 }
14553 arg->prec = arg->prec*10 + (arg->ch - '0');
14554 }
14555 }
14556 }
14557
14558 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14559 if (ctx->fmtcnt >= 0) {
14560 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14561 if (--ctx->fmtcnt >= 0) {
14562 arg->ch = FORMAT_READ(ctx);
14563 ctx->fmtpos++;
14564 }
14565 }
14566 }
14567 if (ctx->fmtcnt < 0) {
14568 PyErr_SetString(PyExc_ValueError,
14569 "incomplete format");
14570 return -1;
14571 }
14572 return 0;
14573
14574#undef FORMAT_READ
14575}
14576
14577/* Format one argument. Supported conversion specifiers:
14578
14579 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014580 - "i", "d", "u": int or float
14581 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014582 - "e", "E", "f", "F", "g", "G": float
14583 - "c": int or str (1 character)
14584
Victor Stinner8dbd4212012-12-04 09:30:24 +010014585 When possible, the output is written directly into the Unicode writer
14586 (ctx->writer). A string is created when padding is required.
14587
Victor Stinnera47082312012-10-04 02:19:54 +020014588 Return 0 if the argument has been formatted into *p_str,
14589 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014590 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014591static int
14592unicode_format_arg_format(struct unicode_formatter_t *ctx,
14593 struct unicode_format_arg_t *arg,
14594 PyObject **p_str)
14595{
14596 PyObject *v;
14597 _PyUnicodeWriter *writer = &ctx->writer;
14598
14599 if (ctx->fmtcnt == 0)
14600 ctx->writer.overallocate = 0;
14601
14602 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014603 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014604 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014605 return 1;
14606 }
14607
14608 v = unicode_format_getnextarg(ctx);
14609 if (v == NULL)
14610 return -1;
14611
Victor Stinnera47082312012-10-04 02:19:54 +020014612
14613 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014614 case 's':
14615 case 'r':
14616 case 'a':
14617 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14618 /* Fast path */
14619 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14620 return -1;
14621 return 1;
14622 }
14623
14624 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14625 *p_str = v;
14626 Py_INCREF(*p_str);
14627 }
14628 else {
14629 if (arg->ch == 's')
14630 *p_str = PyObject_Str(v);
14631 else if (arg->ch == 'r')
14632 *p_str = PyObject_Repr(v);
14633 else
14634 *p_str = PyObject_ASCII(v);
14635 }
14636 break;
14637
14638 case 'i':
14639 case 'd':
14640 case 'u':
14641 case 'o':
14642 case 'x':
14643 case 'X':
14644 {
14645 int ret = mainformatlong(v, arg, p_str, writer);
14646 if (ret != 0)
14647 return ret;
14648 arg->sign = 1;
14649 break;
14650 }
14651
14652 case 'e':
14653 case 'E':
14654 case 'f':
14655 case 'F':
14656 case 'g':
14657 case 'G':
14658 if (arg->width == -1 && arg->prec == -1
14659 && !(arg->flags & (F_SIGN | F_BLANK)))
14660 {
14661 /* Fast path */
14662 if (formatfloat(v, arg, NULL, writer) == -1)
14663 return -1;
14664 return 1;
14665 }
14666
14667 arg->sign = 1;
14668 if (formatfloat(v, arg, p_str, NULL) == -1)
14669 return -1;
14670 break;
14671
14672 case 'c':
14673 {
14674 Py_UCS4 ch = formatchar(v);
14675 if (ch == (Py_UCS4) -1)
14676 return -1;
14677 if (arg->width == -1 && arg->prec == -1) {
14678 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014679 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014680 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014681 return 1;
14682 }
14683 *p_str = PyUnicode_FromOrdinal(ch);
14684 break;
14685 }
14686
14687 default:
14688 PyErr_Format(PyExc_ValueError,
14689 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014690 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014691 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14692 (int)arg->ch,
14693 ctx->fmtpos - 1);
14694 return -1;
14695 }
14696 if (*p_str == NULL)
14697 return -1;
14698 assert (PyUnicode_Check(*p_str));
14699 return 0;
14700}
14701
14702static int
14703unicode_format_arg_output(struct unicode_formatter_t *ctx,
14704 struct unicode_format_arg_t *arg,
14705 PyObject *str)
14706{
14707 Py_ssize_t len;
14708 enum PyUnicode_Kind kind;
14709 void *pbuf;
14710 Py_ssize_t pindex;
14711 Py_UCS4 signchar;
14712 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014713 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014714 Py_ssize_t sublen;
14715 _PyUnicodeWriter *writer = &ctx->writer;
14716 Py_UCS4 fill;
14717
14718 fill = ' ';
14719 if (arg->sign && arg->flags & F_ZERO)
14720 fill = '0';
14721
14722 if (PyUnicode_READY(str) == -1)
14723 return -1;
14724
14725 len = PyUnicode_GET_LENGTH(str);
14726 if ((arg->width == -1 || arg->width <= len)
14727 && (arg->prec == -1 || arg->prec >= len)
14728 && !(arg->flags & (F_SIGN | F_BLANK)))
14729 {
14730 /* Fast path */
14731 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14732 return -1;
14733 return 0;
14734 }
14735
14736 /* Truncate the string for "s", "r" and "a" formats
14737 if the precision is set */
14738 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14739 if (arg->prec >= 0 && len > arg->prec)
14740 len = arg->prec;
14741 }
14742
14743 /* Adjust sign and width */
14744 kind = PyUnicode_KIND(str);
14745 pbuf = PyUnicode_DATA(str);
14746 pindex = 0;
14747 signchar = '\0';
14748 if (arg->sign) {
14749 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14750 if (ch == '-' || ch == '+') {
14751 signchar = ch;
14752 len--;
14753 pindex++;
14754 }
14755 else if (arg->flags & F_SIGN)
14756 signchar = '+';
14757 else if (arg->flags & F_BLANK)
14758 signchar = ' ';
14759 else
14760 arg->sign = 0;
14761 }
14762 if (arg->width < len)
14763 arg->width = len;
14764
14765 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014766 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014767 if (!(arg->flags & F_LJUST)) {
14768 if (arg->sign) {
14769 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014770 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014771 }
14772 else {
14773 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014774 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014775 }
14776 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014777 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14778 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014779 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014780 }
14781
Victor Stinnera47082312012-10-04 02:19:54 +020014782 buflen = arg->width;
14783 if (arg->sign && len == arg->width)
14784 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014785 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014786 return -1;
14787
14788 /* Write the sign if needed */
14789 if (arg->sign) {
14790 if (fill != ' ') {
14791 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14792 writer->pos += 1;
14793 }
14794 if (arg->width > len)
14795 arg->width--;
14796 }
14797
14798 /* Write the numeric prefix for "x", "X" and "o" formats
14799 if the alternate form is used.
14800 For example, write "0x" for the "%#x" format. */
14801 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14802 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14803 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14804 if (fill != ' ') {
14805 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14806 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14807 writer->pos += 2;
14808 pindex += 2;
14809 }
14810 arg->width -= 2;
14811 if (arg->width < 0)
14812 arg->width = 0;
14813 len -= 2;
14814 }
14815
14816 /* Pad left with the fill character if needed */
14817 if (arg->width > len && !(arg->flags & F_LJUST)) {
14818 sublen = arg->width - len;
14819 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14820 writer->pos += sublen;
14821 arg->width = len;
14822 }
14823
14824 /* If padding with spaces: write sign if needed and/or numeric prefix if
14825 the alternate form is used */
14826 if (fill == ' ') {
14827 if (arg->sign) {
14828 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14829 writer->pos += 1;
14830 }
14831 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14832 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14833 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14834 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14835 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14836 writer->pos += 2;
14837 pindex += 2;
14838 }
14839 }
14840
14841 /* Write characters */
14842 if (len) {
14843 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14844 str, pindex, len);
14845 writer->pos += len;
14846 }
14847
14848 /* Pad right with the fill character if needed */
14849 if (arg->width > len) {
14850 sublen = arg->width - len;
14851 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14852 writer->pos += sublen;
14853 }
14854 return 0;
14855}
14856
14857/* Helper of PyUnicode_Format(): format one arg.
14858 Return 0 on success, raise an exception and return -1 on error. */
14859static int
14860unicode_format_arg(struct unicode_formatter_t *ctx)
14861{
14862 struct unicode_format_arg_t arg;
14863 PyObject *str;
14864 int ret;
14865
Victor Stinner8dbd4212012-12-04 09:30:24 +010014866 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14867 arg.flags = 0;
14868 arg.width = -1;
14869 arg.prec = -1;
14870 arg.sign = 0;
14871 str = NULL;
14872
Victor Stinnera47082312012-10-04 02:19:54 +020014873 ret = unicode_format_arg_parse(ctx, &arg);
14874 if (ret == -1)
14875 return -1;
14876
14877 ret = unicode_format_arg_format(ctx, &arg, &str);
14878 if (ret == -1)
14879 return -1;
14880
14881 if (ret != 1) {
14882 ret = unicode_format_arg_output(ctx, &arg, str);
14883 Py_DECREF(str);
14884 if (ret == -1)
14885 return -1;
14886 }
14887
14888 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14889 PyErr_SetString(PyExc_TypeError,
14890 "not all arguments converted during string formatting");
14891 return -1;
14892 }
14893 return 0;
14894}
14895
Alexander Belopolsky40018472011-02-26 01:02:56 +000014896PyObject *
14897PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014898{
Victor Stinnera47082312012-10-04 02:19:54 +020014899 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014900
Guido van Rossumd57fd912000-03-10 22:53:23 +000014901 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014902 PyErr_BadInternalCall();
14903 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014904 }
Victor Stinnera47082312012-10-04 02:19:54 +020014905
14906 ctx.fmtstr = PyUnicode_FromObject(format);
14907 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014908 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014909 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14910 Py_DECREF(ctx.fmtstr);
14911 return NULL;
14912 }
14913 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14914 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14915 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14916 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014917
Victor Stinner8f674cc2013-04-17 23:02:17 +020014918 _PyUnicodeWriter_Init(&ctx.writer);
14919 ctx.writer.min_length = ctx.fmtcnt + 100;
14920 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014921
Guido van Rossumd57fd912000-03-10 22:53:23 +000014922 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014923 ctx.arglen = PyTuple_Size(args);
14924 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014925 }
14926 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014927 ctx.arglen = -1;
14928 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014929 }
Victor Stinnera47082312012-10-04 02:19:54 +020014930 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014931 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014932 ctx.dict = args;
14933 else
14934 ctx.dict = NULL;
14935 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014936
Victor Stinnera47082312012-10-04 02:19:54 +020014937 while (--ctx.fmtcnt >= 0) {
14938 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014939 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014940
14941 nonfmtpos = ctx.fmtpos++;
14942 while (ctx.fmtcnt >= 0 &&
14943 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14944 ctx.fmtpos++;
14945 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014946 }
Victor Stinnera47082312012-10-04 02:19:54 +020014947 if (ctx.fmtcnt < 0) {
14948 ctx.fmtpos--;
14949 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014950 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014951
Victor Stinnercfc4c132013-04-03 01:48:39 +020014952 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14953 nonfmtpos, ctx.fmtpos) < 0)
14954 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014955 }
14956 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014957 ctx.fmtpos++;
14958 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014959 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014960 }
14961 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014962
Victor Stinnera47082312012-10-04 02:19:54 +020014963 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014964 PyErr_SetString(PyExc_TypeError,
14965 "not all arguments converted during string formatting");
14966 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014967 }
14968
Victor Stinnera47082312012-10-04 02:19:54 +020014969 if (ctx.args_owned) {
14970 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014971 }
Victor Stinnera47082312012-10-04 02:19:54 +020014972 Py_DECREF(ctx.fmtstr);
14973 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014974
Benjamin Peterson29060642009-01-31 22:14:21 +000014975 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014976 Py_DECREF(ctx.fmtstr);
14977 _PyUnicodeWriter_Dealloc(&ctx.writer);
14978 if (ctx.args_owned) {
14979 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014980 }
14981 return NULL;
14982}
14983
Jeremy Hylton938ace62002-07-17 16:30:39 +000014984static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014985unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14986
Tim Peters6d6c1a32001-08-02 04:15:00 +000014987static PyObject *
14988unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14989{
Benjamin Peterson29060642009-01-31 22:14:21 +000014990 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014991 static char *kwlist[] = {"object", "encoding", "errors", 0};
14992 char *encoding = NULL;
14993 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014994
Benjamin Peterson14339b62009-01-31 16:36:08 +000014995 if (type != &PyUnicode_Type)
14996 return unicode_subtype_new(type, args, kwds);
14997 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014998 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014999 return NULL;
15000 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015001 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015002 if (encoding == NULL && errors == NULL)
15003 return PyObject_Str(x);
15004 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015005 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015006}
15007
Guido van Rossume023fe02001-08-30 03:12:59 +000015008static PyObject *
15009unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15010{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015011 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015012 Py_ssize_t length, char_size;
15013 int share_wstr, share_utf8;
15014 unsigned int kind;
15015 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015016
Benjamin Peterson14339b62009-01-31 16:36:08 +000015017 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015018
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015019 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015020 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015021 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015022 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015023 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015024 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015025 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015026 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015027
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015028 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015029 if (self == NULL) {
15030 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015031 return NULL;
15032 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015033 kind = PyUnicode_KIND(unicode);
15034 length = PyUnicode_GET_LENGTH(unicode);
15035
15036 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015037#ifdef Py_DEBUG
15038 _PyUnicode_HASH(self) = -1;
15039#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015040 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015041#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015042 _PyUnicode_STATE(self).interned = 0;
15043 _PyUnicode_STATE(self).kind = kind;
15044 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015045 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015046 _PyUnicode_STATE(self).ready = 1;
15047 _PyUnicode_WSTR(self) = NULL;
15048 _PyUnicode_UTF8_LENGTH(self) = 0;
15049 _PyUnicode_UTF8(self) = NULL;
15050 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015051 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015052
15053 share_utf8 = 0;
15054 share_wstr = 0;
15055 if (kind == PyUnicode_1BYTE_KIND) {
15056 char_size = 1;
15057 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15058 share_utf8 = 1;
15059 }
15060 else if (kind == PyUnicode_2BYTE_KIND) {
15061 char_size = 2;
15062 if (sizeof(wchar_t) == 2)
15063 share_wstr = 1;
15064 }
15065 else {
15066 assert(kind == PyUnicode_4BYTE_KIND);
15067 char_size = 4;
15068 if (sizeof(wchar_t) == 4)
15069 share_wstr = 1;
15070 }
15071
15072 /* Ensure we won't overflow the length. */
15073 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15074 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015075 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015077 data = PyObject_MALLOC((length + 1) * char_size);
15078 if (data == NULL) {
15079 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015080 goto onError;
15081 }
15082
Victor Stinnerc3c74152011-10-02 20:39:55 +020015083 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015084 if (share_utf8) {
15085 _PyUnicode_UTF8_LENGTH(self) = length;
15086 _PyUnicode_UTF8(self) = data;
15087 }
15088 if (share_wstr) {
15089 _PyUnicode_WSTR_LENGTH(self) = length;
15090 _PyUnicode_WSTR(self) = (wchar_t *)data;
15091 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015092
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015093 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015094 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015095 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015096#ifdef Py_DEBUG
15097 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15098#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015099 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015100 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015101
15102onError:
15103 Py_DECREF(unicode);
15104 Py_DECREF(self);
15105 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015106}
15107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015108PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015109"str(object='') -> str\n\
15110str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015111\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015112Create a new string object from the given object. If encoding or\n\
15113errors is specified, then the object must expose a data buffer\n\
15114that will be decoded using the given encoding and error handler.\n\
15115Otherwise, returns the result of object.__str__() (if defined)\n\
15116or repr(object).\n\
15117encoding defaults to sys.getdefaultencoding().\n\
15118errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015119
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015120static PyObject *unicode_iter(PyObject *seq);
15121
Guido van Rossumd57fd912000-03-10 22:53:23 +000015122PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015123 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015124 "str", /* tp_name */
15125 sizeof(PyUnicodeObject), /* tp_size */
15126 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015127 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 (destructor)unicode_dealloc, /* tp_dealloc */
15129 0, /* tp_print */
15130 0, /* tp_getattr */
15131 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015132 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015133 unicode_repr, /* tp_repr */
15134 &unicode_as_number, /* tp_as_number */
15135 &unicode_as_sequence, /* tp_as_sequence */
15136 &unicode_as_mapping, /* tp_as_mapping */
15137 (hashfunc) unicode_hash, /* tp_hash*/
15138 0, /* tp_call*/
15139 (reprfunc) unicode_str, /* tp_str */
15140 PyObject_GenericGetAttr, /* tp_getattro */
15141 0, /* tp_setattro */
15142 0, /* tp_as_buffer */
15143 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015144 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 unicode_doc, /* tp_doc */
15146 0, /* tp_traverse */
15147 0, /* tp_clear */
15148 PyUnicode_RichCompare, /* tp_richcompare */
15149 0, /* tp_weaklistoffset */
15150 unicode_iter, /* tp_iter */
15151 0, /* tp_iternext */
15152 unicode_methods, /* tp_methods */
15153 0, /* tp_members */
15154 0, /* tp_getset */
15155 &PyBaseObject_Type, /* tp_base */
15156 0, /* tp_dict */
15157 0, /* tp_descr_get */
15158 0, /* tp_descr_set */
15159 0, /* tp_dictoffset */
15160 0, /* tp_init */
15161 0, /* tp_alloc */
15162 unicode_new, /* tp_new */
15163 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015164};
15165
15166/* Initialize the Unicode implementation */
15167
Victor Stinner3a50e702011-10-18 21:21:00 +020015168int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015169{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015170 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015171 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015172 0x000A, /* LINE FEED */
15173 0x000D, /* CARRIAGE RETURN */
15174 0x001C, /* FILE SEPARATOR */
15175 0x001D, /* GROUP SEPARATOR */
15176 0x001E, /* RECORD SEPARATOR */
15177 0x0085, /* NEXT LINE */
15178 0x2028, /* LINE SEPARATOR */
15179 0x2029, /* PARAGRAPH SEPARATOR */
15180 };
15181
Fred Drakee4315f52000-05-09 19:53:39 +000015182 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015183 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015184 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015185 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015186 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015187
Guido van Rossumcacfc072002-05-24 19:01:59 +000015188 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015189 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015190
15191 /* initialize the linebreak bloom filter */
15192 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015193 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015194 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015195
Christian Heimes26532f72013-07-20 14:57:16 +020015196 if (PyType_Ready(&EncodingMapType) < 0)
15197 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015198
Benjamin Petersonc4311282012-10-30 23:21:10 -040015199 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15200 Py_FatalError("Can't initialize field name iterator type");
15201
15202 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15203 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015204
Victor Stinner3a50e702011-10-18 21:21:00 +020015205 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015206}
15207
15208/* Finalize the Unicode implementation */
15209
Christian Heimesa156e092008-02-16 07:38:31 +000015210int
15211PyUnicode_ClearFreeList(void)
15212{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015213 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015214}
15215
Guido van Rossumd57fd912000-03-10 22:53:23 +000015216void
Thomas Wouters78890102000-07-22 19:25:51 +000015217_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015218{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015219 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015220
Serhiy Storchaka05997252013-01-26 12:14:02 +020015221 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015222
Serhiy Storchaka05997252013-01-26 12:14:02 +020015223 for (i = 0; i < 256; i++)
15224 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015225 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015226 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015227}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015228
Walter Dörwald16807132007-05-25 13:52:07 +000015229void
15230PyUnicode_InternInPlace(PyObject **p)
15231{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015232 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015233 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015234#ifdef Py_DEBUG
15235 assert(s != NULL);
15236 assert(_PyUnicode_CHECK(s));
15237#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015239 return;
15240#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015241 /* If it's a subclass, we don't really know what putting
15242 it in the interned dict might do. */
15243 if (!PyUnicode_CheckExact(s))
15244 return;
15245 if (PyUnicode_CHECK_INTERNED(s))
15246 return;
15247 if (interned == NULL) {
15248 interned = PyDict_New();
15249 if (interned == NULL) {
15250 PyErr_Clear(); /* Don't leave an exception */
15251 return;
15252 }
15253 }
15254 /* It might be that the GetItem call fails even
15255 though the key is present in the dictionary,
15256 namely when this happens during a stack overflow. */
15257 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015258 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015260
Victor Stinnerf0335102013-04-14 19:13:03 +020015261 if (t) {
15262 Py_INCREF(t);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020015263 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015264 return;
15265 }
Walter Dörwald16807132007-05-25 13:52:07 +000015266
Benjamin Peterson14339b62009-01-31 16:36:08 +000015267 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015268 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015269 PyErr_Clear();
15270 PyThreadState_GET()->recursion_critical = 0;
15271 return;
15272 }
15273 PyThreadState_GET()->recursion_critical = 0;
15274 /* The two references in interned are not counted by refcnt.
15275 The deallocator will take care of this */
15276 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015277 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015278}
15279
15280void
15281PyUnicode_InternImmortal(PyObject **p)
15282{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015283 PyUnicode_InternInPlace(p);
15284 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015285 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 Py_INCREF(*p);
15287 }
Walter Dörwald16807132007-05-25 13:52:07 +000015288}
15289
15290PyObject *
15291PyUnicode_InternFromString(const char *cp)
15292{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015293 PyObject *s = PyUnicode_FromString(cp);
15294 if (s == NULL)
15295 return NULL;
15296 PyUnicode_InternInPlace(&s);
15297 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015298}
15299
Alexander Belopolsky40018472011-02-26 01:02:56 +000015300void
15301_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015302{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015303 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015304 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015305 Py_ssize_t i, n;
15306 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015307
Benjamin Peterson14339b62009-01-31 16:36:08 +000015308 if (interned == NULL || !PyDict_Check(interned))
15309 return;
15310 keys = PyDict_Keys(interned);
15311 if (keys == NULL || !PyList_Check(keys)) {
15312 PyErr_Clear();
15313 return;
15314 }
Walter Dörwald16807132007-05-25 13:52:07 +000015315
Benjamin Peterson14339b62009-01-31 16:36:08 +000015316 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15317 detector, interned unicode strings are not forcibly deallocated;
15318 rather, we give them their stolen references back, and then clear
15319 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015320
Benjamin Peterson14339b62009-01-31 16:36:08 +000015321 n = PyList_GET_SIZE(keys);
15322 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015323 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015325 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015326 if (PyUnicode_READY(s) == -1) {
15327 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015328 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015329 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015330 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 case SSTATE_NOT_INTERNED:
15332 /* XXX Shouldn't happen */
15333 break;
15334 case SSTATE_INTERNED_IMMORTAL:
15335 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015336 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015337 break;
15338 case SSTATE_INTERNED_MORTAL:
15339 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015340 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015341 break;
15342 default:
15343 Py_FatalError("Inconsistent interned string state.");
15344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015345 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015346 }
15347 fprintf(stderr, "total size of all interned strings: "
15348 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15349 "mortal/immortal\n", mortal_size, immortal_size);
15350 Py_DECREF(keys);
15351 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015352 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015353}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015354
15355
15356/********************* Unicode Iterator **************************/
15357
15358typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015359 PyObject_HEAD
15360 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015361 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015362} unicodeiterobject;
15363
15364static void
15365unicodeiter_dealloc(unicodeiterobject *it)
15366{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015367 _PyObject_GC_UNTRACK(it);
15368 Py_XDECREF(it->it_seq);
15369 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015370}
15371
15372static int
15373unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15374{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015375 Py_VISIT(it->it_seq);
15376 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015377}
15378
15379static PyObject *
15380unicodeiter_next(unicodeiterobject *it)
15381{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015382 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015383
Benjamin Peterson14339b62009-01-31 16:36:08 +000015384 assert(it != NULL);
15385 seq = it->it_seq;
15386 if (seq == NULL)
15387 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015388 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015390 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15391 int kind = PyUnicode_KIND(seq);
15392 void *data = PyUnicode_DATA(seq);
15393 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15394 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015395 if (item != NULL)
15396 ++it->it_index;
15397 return item;
15398 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015399
Benjamin Peterson14339b62009-01-31 16:36:08 +000015400 Py_DECREF(seq);
15401 it->it_seq = NULL;
15402 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015403}
15404
15405static PyObject *
15406unicodeiter_len(unicodeiterobject *it)
15407{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015408 Py_ssize_t len = 0;
15409 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015410 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015412}
15413
15414PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15415
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015416static PyObject *
15417unicodeiter_reduce(unicodeiterobject *it)
15418{
15419 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015420 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015421 it->it_seq, it->it_index);
15422 } else {
15423 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15424 if (u == NULL)
15425 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015426 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015427 }
15428}
15429
15430PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15431
15432static PyObject *
15433unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15434{
15435 Py_ssize_t index = PyLong_AsSsize_t(state);
15436 if (index == -1 && PyErr_Occurred())
15437 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015438 if (it->it_seq != NULL) {
15439 if (index < 0)
15440 index = 0;
15441 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15442 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15443 it->it_index = index;
15444 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015445 Py_RETURN_NONE;
15446}
15447
15448PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15449
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015450static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015451 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015452 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015453 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15454 reduce_doc},
15455 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15456 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015457 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015458};
15459
15460PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015461 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15462 "str_iterator", /* tp_name */
15463 sizeof(unicodeiterobject), /* tp_basicsize */
15464 0, /* tp_itemsize */
15465 /* methods */
15466 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15467 0, /* tp_print */
15468 0, /* tp_getattr */
15469 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015470 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015471 0, /* tp_repr */
15472 0, /* tp_as_number */
15473 0, /* tp_as_sequence */
15474 0, /* tp_as_mapping */
15475 0, /* tp_hash */
15476 0, /* tp_call */
15477 0, /* tp_str */
15478 PyObject_GenericGetAttr, /* tp_getattro */
15479 0, /* tp_setattro */
15480 0, /* tp_as_buffer */
15481 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15482 0, /* tp_doc */
15483 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15484 0, /* tp_clear */
15485 0, /* tp_richcompare */
15486 0, /* tp_weaklistoffset */
15487 PyObject_SelfIter, /* tp_iter */
15488 (iternextfunc)unicodeiter_next, /* tp_iternext */
15489 unicodeiter_methods, /* tp_methods */
15490 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015491};
15492
15493static PyObject *
15494unicode_iter(PyObject *seq)
15495{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015496 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015497
Benjamin Peterson14339b62009-01-31 16:36:08 +000015498 if (!PyUnicode_Check(seq)) {
15499 PyErr_BadInternalCall();
15500 return NULL;
15501 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015502 if (PyUnicode_READY(seq) == -1)
15503 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015504 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15505 if (it == NULL)
15506 return NULL;
15507 it->it_index = 0;
15508 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015509 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015510 _PyObject_GC_TRACK(it);
15511 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015512}
15513
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015514
15515size_t
15516Py_UNICODE_strlen(const Py_UNICODE *u)
15517{
15518 int res = 0;
15519 while(*u++)
15520 res++;
15521 return res;
15522}
15523
15524Py_UNICODE*
15525Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15526{
15527 Py_UNICODE *u = s1;
15528 while ((*u++ = *s2++));
15529 return s1;
15530}
15531
15532Py_UNICODE*
15533Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15534{
15535 Py_UNICODE *u = s1;
15536 while ((*u++ = *s2++))
15537 if (n-- == 0)
15538 break;
15539 return s1;
15540}
15541
15542Py_UNICODE*
15543Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15544{
15545 Py_UNICODE *u1 = s1;
15546 u1 += Py_UNICODE_strlen(u1);
15547 Py_UNICODE_strcpy(u1, s2);
15548 return s1;
15549}
15550
15551int
15552Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15553{
15554 while (*s1 && *s2 && *s1 == *s2)
15555 s1++, s2++;
15556 if (*s1 && *s2)
15557 return (*s1 < *s2) ? -1 : +1;
15558 if (*s1)
15559 return 1;
15560 if (*s2)
15561 return -1;
15562 return 0;
15563}
15564
15565int
15566Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15567{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015568 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015569 for (; n != 0; n--) {
15570 u1 = *s1;
15571 u2 = *s2;
15572 if (u1 != u2)
15573 return (u1 < u2) ? -1 : +1;
15574 if (u1 == '\0')
15575 return 0;
15576 s1++;
15577 s2++;
15578 }
15579 return 0;
15580}
15581
15582Py_UNICODE*
15583Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15584{
15585 const Py_UNICODE *p;
15586 for (p = s; *p; p++)
15587 if (*p == c)
15588 return (Py_UNICODE*)p;
15589 return NULL;
15590}
15591
15592Py_UNICODE*
15593Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15594{
15595 const Py_UNICODE *p;
15596 p = s + Py_UNICODE_strlen(s);
15597 while (p != s) {
15598 p--;
15599 if (*p == c)
15600 return (Py_UNICODE*)p;
15601 }
15602 return NULL;
15603}
Victor Stinner331ea922010-08-10 16:37:20 +000015604
Victor Stinner71133ff2010-09-01 23:43:53 +000015605Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015606PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015607{
Victor Stinner577db2c2011-10-11 22:12:48 +020015608 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015609 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015611 if (!PyUnicode_Check(unicode)) {
15612 PyErr_BadArgument();
15613 return NULL;
15614 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015615 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015616 if (u == NULL)
15617 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015618 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015619 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015620 PyErr_NoMemory();
15621 return NULL;
15622 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015623 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015624 size *= sizeof(Py_UNICODE);
15625 copy = PyMem_Malloc(size);
15626 if (copy == NULL) {
15627 PyErr_NoMemory();
15628 return NULL;
15629 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015630 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015631 return copy;
15632}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015633
Georg Brandl66c221e2010-10-14 07:04:07 +000015634/* A _string module, to export formatter_parser and formatter_field_name_split
15635 to the string.Formatter class implemented in Python. */
15636
15637static PyMethodDef _string_methods[] = {
15638 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15639 METH_O, PyDoc_STR("split the argument as a field name")},
15640 {"formatter_parser", (PyCFunction) formatter_parser,
15641 METH_O, PyDoc_STR("parse the argument as a format string")},
15642 {NULL, NULL}
15643};
15644
15645static struct PyModuleDef _string_module = {
15646 PyModuleDef_HEAD_INIT,
15647 "_string",
15648 PyDoc_STR("string helper module"),
15649 0,
15650 _string_methods,
15651 NULL,
15652 NULL,
15653 NULL,
15654 NULL
15655};
15656
15657PyMODINIT_FUNC
15658PyInit__string(void)
15659{
15660 return PyModule_Create(&_string_module);
15661}
15662
15663
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015664#ifdef __cplusplus
15665}
15666#endif