blob: 10ba57c5704b42f61404b29782ba2204ba61fcd0 [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 Stinner1a05d6c2016-09-02 12:12:23 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200321 }
322 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200323 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200324 }
325 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200326 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200327 }
328 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200329 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200330 }
331 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200332 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200333 }
334 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200335 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 }
337 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200338 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200339 }
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_OTHER;
341}
342
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300343/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
344 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000345Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000346PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000348#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000349 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000350#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000351 /* This is actually an illegal character, so it should
352 not be passed to unichr. */
353 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000354#endif
355}
356
Victor Stinner910337b2011-10-03 03:20:16 +0200357#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200358int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100359_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200360{
361 PyASCIIObject *ascii;
362 unsigned int kind;
363
364 assert(PyUnicode_Check(op));
365
366 ascii = (PyASCIIObject *)op;
367 kind = ascii->state.kind;
368
Victor Stinnera3b334d2011-10-03 13:53:37 +0200369 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200370 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 assert(ascii->state.ready == 1);
372 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200374 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200376
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 if (ascii->state.compact == 1) {
378 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200379 assert(kind == PyUnicode_1BYTE_KIND
380 || kind == PyUnicode_2BYTE_KIND
381 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200383 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200384 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100385 }
386 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200387 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
388
389 data = unicode->data.any;
390 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100391 assert(ascii->length == 0);
392 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 assert(ascii->state.compact == 0);
394 assert(ascii->state.ascii == 0);
395 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100396 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200397 assert(ascii->wstr != NULL);
398 assert(data == NULL);
399 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200400 }
401 else {
402 assert(kind == PyUnicode_1BYTE_KIND
403 || kind == PyUnicode_2BYTE_KIND
404 || kind == PyUnicode_4BYTE_KIND);
405 assert(ascii->state.compact == 0);
406 assert(ascii->state.ready == 1);
407 assert(data != NULL);
408 if (ascii->state.ascii) {
409 assert (compact->utf8 == data);
410 assert (compact->utf8_length == ascii->length);
411 }
412 else
413 assert (compact->utf8 != data);
414 }
415 }
416 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200417 if (
418#if SIZEOF_WCHAR_T == 2
419 kind == PyUnicode_2BYTE_KIND
420#else
421 kind == PyUnicode_4BYTE_KIND
422#endif
423 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200424 {
425 assert(ascii->wstr == data);
426 assert(compact->wstr_length == ascii->length);
427 } else
428 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200429 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200430
431 if (compact->utf8 == NULL)
432 assert(compact->utf8_length == 0);
433 if (ascii->wstr == NULL)
434 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200435 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200436 /* check that the best kind is used */
437 if (check_content && kind != PyUnicode_WCHAR_KIND)
438 {
439 Py_ssize_t i;
440 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200441 void *data;
442 Py_UCS4 ch;
443
444 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200445 for (i=0; i < ascii->length; i++)
446 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200447 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200448 if (ch > maxchar)
449 maxchar = ch;
450 }
451 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100452 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 255);
455 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200456 else
457 assert(maxchar < 128);
458 }
Victor Stinner77faf692011-11-20 18:56:05 +0100459 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200460 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100461 assert(maxchar <= 0xFFFF);
462 }
463 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200464 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100465 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100466 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200467 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200468 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400469 return 1;
470}
Victor Stinner910337b2011-10-03 03:20:16 +0200471#endif
472
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100473static PyObject*
474unicode_result_wchar(PyObject *unicode)
475{
476#ifndef Py_DEBUG
477 Py_ssize_t len;
478
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100479 len = _PyUnicode_WSTR_LENGTH(unicode);
480 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200482 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100483 }
484
485 if (len == 1) {
486 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100487 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100488 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
489 Py_DECREF(unicode);
490 return latin1_char;
491 }
492 }
493
494 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200495 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 return NULL;
497 }
498#else
Victor Stinneraa771272012-10-04 02:32:58 +0200499 assert(Py_REFCNT(unicode) == 1);
500
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100501 /* don't make the result ready in debug mode to ensure that the caller
502 makes the string ready before using it */
503 assert(_PyUnicode_CheckConsistency(unicode, 1));
504#endif
505 return unicode;
506}
507
508static PyObject*
509unicode_result_ready(PyObject *unicode)
510{
511 Py_ssize_t length;
512
513 length = PyUnicode_GET_LENGTH(unicode);
514 if (length == 0) {
515 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100516 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200517 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 }
519 return unicode_empty;
520 }
521
522 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200523 void *data = PyUnicode_DATA(unicode);
524 int kind = PyUnicode_KIND(unicode);
525 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100526 if (ch < 256) {
527 PyObject *latin1_char = unicode_latin1[ch];
528 if (latin1_char != NULL) {
529 if (unicode != latin1_char) {
530 Py_INCREF(latin1_char);
531 Py_DECREF(unicode);
532 }
533 return latin1_char;
534 }
535 else {
536 assert(_PyUnicode_CheckConsistency(unicode, 1));
537 Py_INCREF(unicode);
538 unicode_latin1[ch] = unicode;
539 return unicode;
540 }
541 }
542 }
543
544 assert(_PyUnicode_CheckConsistency(unicode, 1));
545 return unicode;
546}
547
548static PyObject*
549unicode_result(PyObject *unicode)
550{
551 assert(_PyUnicode_CHECK(unicode));
552 if (PyUnicode_IS_READY(unicode))
553 return unicode_result_ready(unicode);
554 else
555 return unicode_result_wchar(unicode);
556}
557
Victor Stinnerc4b49542011-12-11 22:44:26 +0100558static PyObject*
559unicode_result_unchanged(PyObject *unicode)
560{
561 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500562 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563 return NULL;
564 Py_INCREF(unicode);
565 return unicode;
566 }
567 else
568 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100569 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100570}
571
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
573 ASCII, Latin1, UTF-8, etc. */
574static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200575backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200576 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
577{
Victor Stinnerad771582015-10-09 12:38:53 +0200578 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200579 Py_UCS4 ch;
580 enum PyUnicode_Kind kind;
581 void *data;
582
583 assert(PyUnicode_IS_READY(unicode));
584 kind = PyUnicode_KIND(unicode);
585 data = PyUnicode_DATA(unicode);
586
587 size = 0;
588 /* determine replacement size */
589 for (i = collstart; i < collend; ++i) {
590 Py_ssize_t incr;
591
592 ch = PyUnicode_READ(kind, data, i);
593 if (ch < 0x100)
594 incr = 2+2;
595 else if (ch < 0x10000)
596 incr = 2+4;
597 else {
598 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200599 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200600 }
601 if (size > PY_SSIZE_T_MAX - incr) {
602 PyErr_SetString(PyExc_OverflowError,
603 "encoded result is too long for a Python string");
604 return NULL;
605 }
606 size += incr;
607 }
608
Victor Stinnerad771582015-10-09 12:38:53 +0200609 str = _PyBytesWriter_Prepare(writer, str, size);
610 if (str == NULL)
611 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200612
613 /* generate replacement */
614 for (i = collstart; i < collend; ++i) {
615 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200616 *str++ = '\\';
617 if (ch >= 0x00010000) {
618 *str++ = 'U';
619 *str++ = Py_hexdigits[(ch>>28)&0xf];
620 *str++ = Py_hexdigits[(ch>>24)&0xf];
621 *str++ = Py_hexdigits[(ch>>20)&0xf];
622 *str++ = Py_hexdigits[(ch>>16)&0xf];
623 *str++ = Py_hexdigits[(ch>>12)&0xf];
624 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200625 }
Victor Stinner797485e2015-10-09 03:17:30 +0200626 else if (ch >= 0x100) {
627 *str++ = 'u';
628 *str++ = Py_hexdigits[(ch>>12)&0xf];
629 *str++ = Py_hexdigits[(ch>>8)&0xf];
630 }
631 else
632 *str++ = 'x';
633 *str++ = Py_hexdigits[(ch>>4)&0xf];
634 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200635 }
636 return str;
637}
638
639/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
640 ASCII, Latin1, UTF-8, etc. */
641static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200642xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200643 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
644{
Victor Stinnerad771582015-10-09 12:38:53 +0200645 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200646 Py_UCS4 ch;
647 enum PyUnicode_Kind kind;
648 void *data;
649
650 assert(PyUnicode_IS_READY(unicode));
651 kind = PyUnicode_KIND(unicode);
652 data = PyUnicode_DATA(unicode);
653
654 size = 0;
655 /* determine replacement size */
656 for (i = collstart; i < collend; ++i) {
657 Py_ssize_t incr;
658
659 ch = PyUnicode_READ(kind, data, i);
660 if (ch < 10)
661 incr = 2+1+1;
662 else if (ch < 100)
663 incr = 2+2+1;
664 else if (ch < 1000)
665 incr = 2+3+1;
666 else if (ch < 10000)
667 incr = 2+4+1;
668 else if (ch < 100000)
669 incr = 2+5+1;
670 else if (ch < 1000000)
671 incr = 2+6+1;
672 else {
673 assert(ch <= MAX_UNICODE);
674 incr = 2+7+1;
675 }
676 if (size > PY_SSIZE_T_MAX - incr) {
677 PyErr_SetString(PyExc_OverflowError,
678 "encoded result is too long for a Python string");
679 return NULL;
680 }
681 size += incr;
682 }
683
Victor Stinnerad771582015-10-09 12:38:53 +0200684 str = _PyBytesWriter_Prepare(writer, str, size);
685 if (str == NULL)
686 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200687
688 /* generate replacement */
689 for (i = collstart; i < collend; ++i) {
690 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
691 }
692 return str;
693}
694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695/* --- Bloom Filters ----------------------------------------------------- */
696
697/* stuff to implement simple "bloom filters" for Unicode characters.
698 to keep things simple, we use a single bitmask, using the least 5
699 bits from each unicode characters as the bit index. */
700
701/* the linebreak mask is set up by Unicode_Init below */
702
Antoine Pitrouf068f942010-01-13 14:19:12 +0000703#if LONG_BIT >= 128
704#define BLOOM_WIDTH 128
705#elif LONG_BIT >= 64
706#define BLOOM_WIDTH 64
707#elif LONG_BIT >= 32
708#define BLOOM_WIDTH 32
709#else
710#error "LONG_BIT is smaller than 32"
711#endif
712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713#define BLOOM_MASK unsigned long
714
Serhiy Storchaka05997252013-01-26 12:14:02 +0200715static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716
Antoine Pitrouf068f942010-01-13 14:19:12 +0000717#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718
Benjamin Peterson29060642009-01-31 22:14:21 +0000719#define BLOOM_LINEBREAK(ch) \
720 ((ch) < 128U ? ascii_linebreak[(ch)] : \
721 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722
Alexander Belopolsky40018472011-02-26 01:02:56 +0000723Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200724make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725{
Victor Stinnera85af502013-04-09 21:53:54 +0200726#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
727 do { \
728 TYPE *data = (TYPE *)PTR; \
729 TYPE *end = data + LEN; \
730 Py_UCS4 ch; \
731 for (; data != end; data++) { \
732 ch = *data; \
733 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
734 } \
735 break; \
736 } while (0)
737
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 /* calculate simple bloom-style bitmask for a given unicode string */
739
Antoine Pitrouf068f942010-01-13 14:19:12 +0000740 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741
742 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200743 switch (kind) {
744 case PyUnicode_1BYTE_KIND:
745 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
746 break;
747 case PyUnicode_2BYTE_KIND:
748 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
749 break;
750 case PyUnicode_4BYTE_KIND:
751 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
752 break;
753 default:
754 assert(0);
755 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200757
758#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759}
760
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300761static int
762ensure_unicode(PyObject *obj)
763{
764 if (!PyUnicode_Check(obj)) {
765 PyErr_Format(PyExc_TypeError,
766 "must be str, not %.100s",
767 Py_TYPE(obj)->tp_name);
768 return -1;
769 }
770 return PyUnicode_READY(obj);
771}
772
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773/* Compilation of templated routines */
774
775#include "stringlib/asciilib.h"
776#include "stringlib/fastsearch.h"
777#include "stringlib/partition.h"
778#include "stringlib/split.h"
779#include "stringlib/count.h"
780#include "stringlib/find.h"
781#include "stringlib/find_max_char.h"
782#include "stringlib/localeutil.h"
783#include "stringlib/undef.h"
784
785#include "stringlib/ucs1lib.h"
786#include "stringlib/fastsearch.h"
787#include "stringlib/partition.h"
788#include "stringlib/split.h"
789#include "stringlib/count.h"
790#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300791#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200792#include "stringlib/find_max_char.h"
793#include "stringlib/localeutil.h"
794#include "stringlib/undef.h"
795
796#include "stringlib/ucs2lib.h"
797#include "stringlib/fastsearch.h"
798#include "stringlib/partition.h"
799#include "stringlib/split.h"
800#include "stringlib/count.h"
801#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300802#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200803#include "stringlib/find_max_char.h"
804#include "stringlib/localeutil.h"
805#include "stringlib/undef.h"
806
807#include "stringlib/ucs4lib.h"
808#include "stringlib/fastsearch.h"
809#include "stringlib/partition.h"
810#include "stringlib/split.h"
811#include "stringlib/count.h"
812#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300813#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200814#include "stringlib/find_max_char.h"
815#include "stringlib/localeutil.h"
816#include "stringlib/undef.h"
817
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200818#include "stringlib/unicodedefs.h"
819#include "stringlib/fastsearch.h"
820#include "stringlib/count.h"
821#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100822#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823
Guido van Rossumd57fd912000-03-10 22:53:23 +0000824/* --- Unicode Object ----------------------------------------------------- */
825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200827fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200829Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200830 Py_ssize_t size, Py_UCS4 ch,
831 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200833 switch (kind) {
834 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200835 if ((Py_UCS1) ch != ch)
836 return -1;
837 if (direction > 0)
838 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
839 else
840 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200841 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200842 if ((Py_UCS2) ch != ch)
843 return -1;
844 if (direction > 0)
845 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
846 else
847 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200849 if (direction > 0)
850 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
851 else
852 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200853 default:
854 assert(0);
855 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200857}
858
Victor Stinnerafffce42012-10-03 23:03:17 +0200859#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000860/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200861 earlier.
862
863 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
864 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
865 invalid character in Unicode 6.0. */
866static void
867unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
868{
869 int kind = PyUnicode_KIND(unicode);
870 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
871 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
872 if (length <= old_length)
873 return;
874 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
875}
876#endif
877
Victor Stinnerfe226c02011-10-03 03:52:20 +0200878static PyObject*
879resize_compact(PyObject *unicode, Py_ssize_t length)
880{
881 Py_ssize_t char_size;
882 Py_ssize_t struct_size;
883 Py_ssize_t new_size;
884 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100885 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200886#ifdef Py_DEBUG
887 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
888#endif
889
Victor Stinner79891572012-05-03 13:43:07 +0200890 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200891 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100892 assert(PyUnicode_IS_COMPACT(unicode));
893
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200894 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100895 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200896 struct_size = sizeof(PyASCIIObject);
897 else
898 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200899 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200900
Victor Stinnerfe226c02011-10-03 03:52:20 +0200901 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
902 PyErr_NoMemory();
903 return NULL;
904 }
905 new_size = (struct_size + (length + 1) * char_size);
906
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200907 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
908 PyObject_DEL(_PyUnicode_UTF8(unicode));
909 _PyUnicode_UTF8(unicode) = NULL;
910 _PyUnicode_UTF8_LENGTH(unicode) = 0;
911 }
Victor Stinner84def372011-12-11 20:04:56 +0100912 _Py_DEC_REFTOTAL;
913 _Py_ForgetReference(unicode);
914
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300915 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100916 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100917 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200918 PyErr_NoMemory();
919 return NULL;
920 }
Victor Stinner84def372011-12-11 20:04:56 +0100921 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200922 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100923
Victor Stinnerfe226c02011-10-03 03:52:20 +0200924 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200925 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200926 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100927 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200928 _PyUnicode_WSTR_LENGTH(unicode) = length;
929 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100930 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
931 PyObject_DEL(_PyUnicode_WSTR(unicode));
932 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100933 if (!PyUnicode_IS_ASCII(unicode))
934 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100935 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200936#ifdef Py_DEBUG
937 unicode_fill_invalid(unicode, old_length);
938#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200939 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
940 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200941 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200942 return unicode;
943}
944
Alexander Belopolsky40018472011-02-26 01:02:56 +0000945static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200946resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000947{
Victor Stinner95663112011-10-04 01:03:50 +0200948 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100949 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200950 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200951 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000952
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 if (PyUnicode_IS_READY(unicode)) {
954 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200955 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200957#ifdef Py_DEBUG
958 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
959#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200960
961 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200962 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200963 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
964 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965
966 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
967 PyErr_NoMemory();
968 return -1;
969 }
970 new_size = (length + 1) * char_size;
971
Victor Stinner7a9105a2011-12-12 00:13:42 +0100972 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
973 {
974 PyObject_DEL(_PyUnicode_UTF8(unicode));
975 _PyUnicode_UTF8(unicode) = NULL;
976 _PyUnicode_UTF8_LENGTH(unicode) = 0;
977 }
978
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979 data = (PyObject *)PyObject_REALLOC(data, new_size);
980 if (data == NULL) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200985 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200986 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200987 _PyUnicode_WSTR_LENGTH(unicode) = length;
988 }
989 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200990 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200991 _PyUnicode_UTF8_LENGTH(unicode) = length;
992 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 _PyUnicode_LENGTH(unicode) = length;
994 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200995#ifdef Py_DEBUG
996 unicode_fill_invalid(unicode, old_length);
997#endif
Victor Stinner95663112011-10-04 01:03:50 +0200998 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200999 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 }
Victor Stinner95663112011-10-04 01:03:50 +02001003 assert(_PyUnicode_WSTR(unicode) != NULL);
1004
1005 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001006 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001007 PyErr_NoMemory();
1008 return -1;
1009 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001010 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001011 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001012 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001013 if (!wstr) {
1014 PyErr_NoMemory();
1015 return -1;
1016 }
1017 _PyUnicode_WSTR(unicode) = wstr;
1018 _PyUnicode_WSTR(unicode)[length] = 0;
1019 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001020 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001021 return 0;
1022}
1023
Victor Stinnerfe226c02011-10-03 03:52:20 +02001024static PyObject*
1025resize_copy(PyObject *unicode, Py_ssize_t length)
1026{
1027 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001028 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001029 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001030
Benjamin Petersonbac79492012-01-14 13:34:47 -05001031 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001032 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001033
1034 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1035 if (copy == NULL)
1036 return NULL;
1037
1038 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001039 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001040 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001041 }
1042 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001043 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001045 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 if (w == NULL)
1047 return NULL;
1048 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1049 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001050 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1051 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001052 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 }
1054}
1055
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001057 Ux0000 terminated; some code (e.g. new_identifier)
1058 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001059
1060 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001061 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001062
1063*/
1064
Alexander Belopolsky40018472011-02-26 01:02:56 +00001065static PyUnicodeObject *
1066_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001067{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001068 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001070
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072 if (length == 0 && unicode_empty != NULL) {
1073 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001074 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075 }
1076
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001077 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001078 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001079 return (PyUnicodeObject *)PyErr_NoMemory();
1080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 if (length < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to _PyUnicode_New");
1084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 }
1086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1088 if (unicode == NULL)
1089 return NULL;
1090 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001091
1092 _PyUnicode_WSTR_LENGTH(unicode) = length;
1093 _PyUnicode_HASH(unicode) = -1;
1094 _PyUnicode_STATE(unicode).interned = 0;
1095 _PyUnicode_STATE(unicode).kind = 0;
1096 _PyUnicode_STATE(unicode).compact = 0;
1097 _PyUnicode_STATE(unicode).ready = 0;
1098 _PyUnicode_STATE(unicode).ascii = 0;
1099 _PyUnicode_DATA_ANY(unicode) = NULL;
1100 _PyUnicode_LENGTH(unicode) = 0;
1101 _PyUnicode_UTF8(unicode) = NULL;
1102 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1105 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001106 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001107 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001108 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110
Jeremy Hyltond8082792003-09-16 19:41:39 +00001111 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001112 * the caller fails before initializing str -- unicode_resize()
1113 * reads str[0], and the Keep-Alive optimization can keep memory
1114 * allocated for str alive across a call to unicode_dealloc(unicode).
1115 * We don't want unicode_resize to read uninitialized memory in
1116 * that case.
1117 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 _PyUnicode_WSTR(unicode)[0] = 0;
1119 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001120
Victor Stinner7931d9a2011-11-04 00:22:48 +01001121 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001122 return unicode;
1123}
1124
Victor Stinnerf42dc442011-10-02 23:33:16 +02001125static const char*
1126unicode_kind_name(PyObject *unicode)
1127{
Victor Stinner42dfd712011-10-03 14:41:45 +02001128 /* don't check consistency: unicode_kind_name() is called from
1129 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001130 if (!PyUnicode_IS_COMPACT(unicode))
1131 {
1132 if (!PyUnicode_IS_READY(unicode))
1133 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001134 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001135 {
1136 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001137 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138 return "legacy ascii";
1139 else
1140 return "legacy latin1";
1141 case PyUnicode_2BYTE_KIND:
1142 return "legacy UCS2";
1143 case PyUnicode_4BYTE_KIND:
1144 return "legacy UCS4";
1145 default:
1146 return "<legacy invalid kind>";
1147 }
1148 }
1149 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001150 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001152 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001153 return "ascii";
1154 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001155 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001157 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001158 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001159 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001160 default:
1161 return "<invalid compact kind>";
1162 }
1163}
1164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166/* Functions wrapping macros for use in debugger */
1167char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001168 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169}
1170
1171void *_PyUnicode_compact_data(void *unicode) {
1172 return _PyUnicode_COMPACT_DATA(unicode);
1173}
1174void *_PyUnicode_data(void *unicode){
1175 printf("obj %p\n", unicode);
1176 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1177 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1178 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1179 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1180 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1181 return PyUnicode_DATA(unicode);
1182}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001183
1184void
1185_PyUnicode_Dump(PyObject *op)
1186{
1187 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001188 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1189 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1190 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001191
Victor Stinnera849a4b2011-10-03 12:12:11 +02001192 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001193 {
1194 if (ascii->state.ascii)
1195 data = (ascii + 1);
1196 else
1197 data = (compact + 1);
1198 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001199 else
1200 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001201 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1202 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001203
Victor Stinnera849a4b2011-10-03 12:12:11 +02001204 if (ascii->wstr == data)
1205 printf("shared ");
1206 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001207
Victor Stinnera3b334d2011-10-03 13:53:37 +02001208 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001209 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001210 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1211 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001212 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1213 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001214 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001215 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001216}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217#endif
1218
1219PyObject *
1220PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1221{
1222 PyObject *obj;
1223 PyCompactUnicodeObject *unicode;
1224 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001225 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001226 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001227 Py_ssize_t char_size;
1228 Py_ssize_t struct_size;
1229
1230 /* Optimization for empty strings */
1231 if (size == 0 && unicode_empty != NULL) {
1232 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001233 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234 }
1235
Victor Stinner9e9d6892011-10-04 01:02:02 +02001236 is_ascii = 0;
1237 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 struct_size = sizeof(PyCompactUnicodeObject);
1239 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001240 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 char_size = 1;
1242 is_ascii = 1;
1243 struct_size = sizeof(PyASCIIObject);
1244 }
1245 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001246 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 char_size = 1;
1248 }
1249 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001250 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 char_size = 2;
1252 if (sizeof(wchar_t) == 2)
1253 is_sharing = 1;
1254 }
1255 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001256 if (maxchar > MAX_UNICODE) {
1257 PyErr_SetString(PyExc_SystemError,
1258 "invalid maximum character passed to PyUnicode_New");
1259 return NULL;
1260 }
Victor Stinner8f825062012-04-27 13:55:39 +02001261 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262 char_size = 4;
1263 if (sizeof(wchar_t) == 4)
1264 is_sharing = 1;
1265 }
1266
1267 /* Ensure we won't overflow the size. */
1268 if (size < 0) {
1269 PyErr_SetString(PyExc_SystemError,
1270 "Negative size passed to PyUnicode_New");
1271 return NULL;
1272 }
1273 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1274 return PyErr_NoMemory();
1275
1276 /* Duplicated allocation code from _PyObject_New() instead of a call to
1277 * PyObject_New() so we are able to allocate space for the object and
1278 * it's data buffer.
1279 */
1280 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1281 if (obj == NULL)
1282 return PyErr_NoMemory();
1283 obj = PyObject_INIT(obj, &PyUnicode_Type);
1284 if (obj == NULL)
1285 return NULL;
1286
1287 unicode = (PyCompactUnicodeObject *)obj;
1288 if (is_ascii)
1289 data = ((PyASCIIObject*)obj) + 1;
1290 else
1291 data = unicode + 1;
1292 _PyUnicode_LENGTH(unicode) = size;
1293 _PyUnicode_HASH(unicode) = -1;
1294 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001295 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296 _PyUnicode_STATE(unicode).compact = 1;
1297 _PyUnicode_STATE(unicode).ready = 1;
1298 _PyUnicode_STATE(unicode).ascii = is_ascii;
1299 if (is_ascii) {
1300 ((char*)data)[size] = 0;
1301 _PyUnicode_WSTR(unicode) = NULL;
1302 }
Victor Stinner8f825062012-04-27 13:55:39 +02001303 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 ((char*)data)[size] = 0;
1305 _PyUnicode_WSTR(unicode) = NULL;
1306 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001308 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 else {
1311 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001312 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001313 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001315 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 ((Py_UCS4*)data)[size] = 0;
1317 if (is_sharing) {
1318 _PyUnicode_WSTR_LENGTH(unicode) = size;
1319 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1320 }
1321 else {
1322 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1323 _PyUnicode_WSTR(unicode) = NULL;
1324 }
1325 }
Victor Stinner8f825062012-04-27 13:55:39 +02001326#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001327 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001328#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001329 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 return obj;
1331}
1332
1333#if SIZEOF_WCHAR_T == 2
1334/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1335 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001336 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
1338 This function assumes that unicode can hold one more code point than wstr
1339 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001340static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001342 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343{
1344 const wchar_t *iter;
1345 Py_UCS4 *ucs4_out;
1346
Victor Stinner910337b2011-10-03 03:20:16 +02001347 assert(unicode != NULL);
1348 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1350 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1351
1352 for (iter = begin; iter < end; ) {
1353 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1354 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001355 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1356 && (iter+1) < end
1357 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 {
Victor Stinner551ac952011-11-29 22:58:13 +01001359 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001360 iter += 2;
1361 }
1362 else {
1363 *ucs4_out++ = *iter;
1364 iter++;
1365 }
1366 }
1367 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1368 _PyUnicode_GET_LENGTH(unicode)));
1369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370}
1371#endif
1372
Victor Stinnercd9950f2011-10-02 00:34:53 +02001373static int
Victor Stinner488fa492011-12-12 00:01:39 +01001374unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001375{
Victor Stinner488fa492011-12-12 00:01:39 +01001376 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001377 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001378 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001379 return -1;
1380 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001381 return 0;
1382}
1383
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001384static int
1385_copy_characters(PyObject *to, Py_ssize_t to_start,
1386 PyObject *from, Py_ssize_t from_start,
1387 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001388{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001389 unsigned int from_kind, to_kind;
1390 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinneree4544c2012-05-09 22:24:08 +02001392 assert(0 <= how_many);
1393 assert(0 <= from_start);
1394 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001395 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001397 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398
Victor Stinnerd3f08822012-05-29 12:57:52 +02001399 assert(PyUnicode_Check(to));
1400 assert(PyUnicode_IS_READY(to));
1401 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1402
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001403 if (how_many == 0)
1404 return 0;
1405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001407 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001409 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerf1852262012-06-16 16:38:26 +02001411#ifdef Py_DEBUG
1412 if (!check_maxchar
1413 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1414 {
1415 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1416 Py_UCS4 ch;
1417 Py_ssize_t i;
1418 for (i=0; i < how_many; i++) {
1419 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1420 assert(ch <= to_maxchar);
1421 }
1422 }
1423#endif
1424
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001425 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001426 if (check_maxchar
1427 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1428 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001429 /* Writing Latin-1 characters into an ASCII string requires to
1430 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001431 Py_UCS4 max_char;
1432 max_char = ucs1lib_find_max_char(from_data,
1433 (Py_UCS1*)from_data + how_many);
1434 if (max_char >= 128)
1435 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001436 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001437 Py_MEMCPY((char*)to_data + to_kind * to_start,
1438 (char*)from_data + from_kind * from_start,
1439 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001441 else if (from_kind == PyUnicode_1BYTE_KIND
1442 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001443 {
1444 _PyUnicode_CONVERT_BYTES(
1445 Py_UCS1, Py_UCS2,
1446 PyUnicode_1BYTE_DATA(from) + from_start,
1447 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448 PyUnicode_2BYTE_DATA(to) + to_start
1449 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001450 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001451 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001452 && to_kind == PyUnicode_4BYTE_KIND)
1453 {
1454 _PyUnicode_CONVERT_BYTES(
1455 Py_UCS1, Py_UCS4,
1456 PyUnicode_1BYTE_DATA(from) + from_start,
1457 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458 PyUnicode_4BYTE_DATA(to) + to_start
1459 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001460 }
1461 else if (from_kind == PyUnicode_2BYTE_KIND
1462 && to_kind == PyUnicode_4BYTE_KIND)
1463 {
1464 _PyUnicode_CONVERT_BYTES(
1465 Py_UCS2, Py_UCS4,
1466 PyUnicode_2BYTE_DATA(from) + from_start,
1467 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468 PyUnicode_4BYTE_DATA(to) + to_start
1469 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001470 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001471 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001472 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001474 if (!check_maxchar) {
1475 if (from_kind == PyUnicode_2BYTE_KIND
1476 && to_kind == PyUnicode_1BYTE_KIND)
1477 {
1478 _PyUnicode_CONVERT_BYTES(
1479 Py_UCS2, Py_UCS1,
1480 PyUnicode_2BYTE_DATA(from) + from_start,
1481 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482 PyUnicode_1BYTE_DATA(to) + to_start
1483 );
1484 }
1485 else if (from_kind == PyUnicode_4BYTE_KIND
1486 && to_kind == PyUnicode_1BYTE_KIND)
1487 {
1488 _PyUnicode_CONVERT_BYTES(
1489 Py_UCS4, Py_UCS1,
1490 PyUnicode_4BYTE_DATA(from) + from_start,
1491 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492 PyUnicode_1BYTE_DATA(to) + to_start
1493 );
1494 }
1495 else if (from_kind == PyUnicode_4BYTE_KIND
1496 && to_kind == PyUnicode_2BYTE_KIND)
1497 {
1498 _PyUnicode_CONVERT_BYTES(
1499 Py_UCS4, Py_UCS2,
1500 PyUnicode_4BYTE_DATA(from) + from_start,
1501 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502 PyUnicode_2BYTE_DATA(to) + to_start
1503 );
1504 }
1505 else {
1506 assert(0);
1507 return -1;
1508 }
1509 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001510 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001511 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 Py_ssize_t i;
1514
Victor Stinnera0702ab2011-09-29 14:14:38 +02001515 for (i=0; i < how_many; i++) {
1516 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001517 if (ch > to_maxchar)
1518 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001519 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1520 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001521 }
1522 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523 return 0;
1524}
1525
Victor Stinnerd3f08822012-05-29 12:57:52 +02001526void
1527_PyUnicode_FastCopyCharacters(
1528 PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530{
1531 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1532}
1533
1534Py_ssize_t
1535PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1536 PyObject *from, Py_ssize_t from_start,
1537 Py_ssize_t how_many)
1538{
1539 int err;
1540
1541 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545
Benjamin Petersonbac79492012-01-14 13:34:47 -05001546 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001548 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 return -1;
1550
Victor Stinnerd3f08822012-05-29 12:57:52 +02001551 if (from_start < 0) {
1552 PyErr_SetString(PyExc_IndexError, "string index out of range");
1553 return -1;
1554 }
1555 if (to_start < 0) {
1556 PyErr_SetString(PyExc_IndexError, "string index out of range");
1557 return -1;
1558 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1560 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1561 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001562 "Cannot write %zi characters at %zi "
1563 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 how_many, to_start, PyUnicode_GET_LENGTH(to));
1565 return -1;
1566 }
1567
1568 if (how_many == 0)
1569 return 0;
1570
Victor Stinner488fa492011-12-12 00:01:39 +01001571 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001572 return -1;
1573
1574 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1575 if (err) {
1576 PyErr_Format(PyExc_SystemError,
1577 "Cannot copy %s characters "
1578 "into a string of %s characters",
1579 unicode_kind_name(from),
1580 unicode_kind_name(to));
1581 return -1;
1582 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001583 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584}
1585
Victor Stinner17222162011-09-28 22:15:37 +02001586/* Find the maximum code point and count the number of surrogate pairs so a
1587 correct string length can be computed before converting a string to UCS4.
1588 This function counts single surrogates as a character and not as a pair.
1589
1590 Return 0 on success, or -1 on error. */
1591static int
1592find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1593 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594{
1595 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001596 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerc53be962011-10-02 21:33:54 +02001598 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 *num_surrogates = 0;
1600 *maxchar = 0;
1601
1602 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001604 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1605 && (iter+1) < end
1606 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1607 {
1608 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1609 ++(*num_surrogates);
1610 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001611 }
1612 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001614 {
1615 ch = *iter;
1616 iter++;
1617 }
1618 if (ch > *maxchar) {
1619 *maxchar = ch;
1620 if (*maxchar > MAX_UNICODE) {
1621 PyErr_Format(PyExc_ValueError,
1622 "character U+%x is not in range [U+0000; U+10ffff]",
1623 ch);
1624 return -1;
1625 }
1626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 return 0;
1629}
1630
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001631int
1632_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001633{
1634 wchar_t *end;
1635 Py_UCS4 maxchar = 0;
1636 Py_ssize_t num_surrogates;
1637#if SIZEOF_WCHAR_T == 2
1638 Py_ssize_t length_wo_surrogates;
1639#endif
1640
Georg Brandl7597add2011-10-05 16:36:47 +02001641 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001642 strings were created using _PyObject_New() and where no canonical
1643 representation (the str field) has been set yet aka strings
1644 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001645 assert(_PyUnicode_CHECK(unicode));
1646 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001647 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001648 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001649 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001650 /* Actually, it should neither be interned nor be anything else: */
1651 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001654 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001655 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657
1658 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001659 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1660 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 PyErr_NoMemory();
1662 return -1;
1663 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001664 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 _PyUnicode_WSTR(unicode), end,
1666 PyUnicode_1BYTE_DATA(unicode));
1667 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1668 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1669 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1670 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001671 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001672 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001673 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674 }
1675 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001676 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8(unicode) = NULL;
1678 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001679 }
1680 PyObject_FREE(_PyUnicode_WSTR(unicode));
1681 _PyUnicode_WSTR(unicode) = NULL;
1682 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1683 }
1684 /* In this case we might have to convert down from 4-byte native
1685 wchar_t to 2-byte unicode. */
1686 else if (maxchar < 65536) {
1687 assert(num_surrogates == 0 &&
1688 "FindMaxCharAndNumSurrogatePairs() messed up");
1689
Victor Stinner506f5922011-09-28 22:34:18 +02001690#if SIZEOF_WCHAR_T == 2
1691 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001692 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001693 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1694 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1695 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001696 _PyUnicode_UTF8(unicode) = NULL;
1697 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001698#else
1699 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001700 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001701 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001702 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001703 PyErr_NoMemory();
1704 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705 }
Victor Stinner506f5922011-09-28 22:34:18 +02001706 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1707 _PyUnicode_WSTR(unicode), end,
1708 PyUnicode_2BYTE_DATA(unicode));
1709 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1710 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1711 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001712 _PyUnicode_UTF8(unicode) = NULL;
1713 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001714 PyObject_FREE(_PyUnicode_WSTR(unicode));
1715 _PyUnicode_WSTR(unicode) = NULL;
1716 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1717#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718 }
1719 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1720 else {
1721#if SIZEOF_WCHAR_T == 2
1722 /* in case the native representation is 2-bytes, we need to allocate a
1723 new normalized 4-byte version. */
1724 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001725 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1726 PyErr_NoMemory();
1727 return -1;
1728 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001729 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1730 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001731 PyErr_NoMemory();
1732 return -1;
1733 }
1734 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1735 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001736 _PyUnicode_UTF8(unicode) = NULL;
1737 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001738 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1739 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001740 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001741 PyObject_FREE(_PyUnicode_WSTR(unicode));
1742 _PyUnicode_WSTR(unicode) = NULL;
1743 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1744#else
1745 assert(num_surrogates == 0);
1746
Victor Stinnerc3c74152011-10-02 20:39:55 +02001747 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001749 _PyUnicode_UTF8(unicode) = NULL;
1750 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1752#endif
1753 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1754 }
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001756 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 return 0;
1758}
1759
Alexander Belopolsky40018472011-02-26 01:02:56 +00001760static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001761unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001762{
Walter Dörwald16807132007-05-25 13:52:07 +00001763 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001764 case SSTATE_NOT_INTERNED:
1765 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001766
Benjamin Peterson29060642009-01-31 22:14:21 +00001767 case SSTATE_INTERNED_MORTAL:
1768 /* revive dead object temporarily for DelItem */
1769 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001770 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 Py_FatalError(
1772 "deletion of interned string failed");
1773 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001774
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 case SSTATE_INTERNED_IMMORTAL:
1776 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001777
Benjamin Peterson29060642009-01-31 22:14:21 +00001778 default:
1779 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001780 }
1781
Victor Stinner03490912011-10-03 23:45:12 +02001782 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001784 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001785 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001786 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1787 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001789 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001790}
1791
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001792#ifdef Py_DEBUG
1793static int
1794unicode_is_singleton(PyObject *unicode)
1795{
1796 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1797 if (unicode == unicode_empty)
1798 return 1;
1799 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1800 {
1801 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1802 if (ch < 256 && unicode_latin1[ch] == unicode)
1803 return 1;
1804 }
1805 return 0;
1806}
1807#endif
1808
Alexander Belopolsky40018472011-02-26 01:02:56 +00001809static int
Victor Stinner488fa492011-12-12 00:01:39 +01001810unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001811{
Victor Stinner488fa492011-12-12 00:01:39 +01001812 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001813 if (Py_REFCNT(unicode) != 1)
1814 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001815 if (_PyUnicode_HASH(unicode) != -1)
1816 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001817 if (PyUnicode_CHECK_INTERNED(unicode))
1818 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001819 if (!PyUnicode_CheckExact(unicode))
1820 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001821#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001822 /* singleton refcount is greater than 1 */
1823 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001824#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001825 return 1;
1826}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001827
Victor Stinnerfe226c02011-10-03 03:52:20 +02001828static int
1829unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1830{
1831 PyObject *unicode;
1832 Py_ssize_t old_length;
1833
1834 assert(p_unicode != NULL);
1835 unicode = *p_unicode;
1836
1837 assert(unicode != NULL);
1838 assert(PyUnicode_Check(unicode));
1839 assert(0 <= length);
1840
Victor Stinner910337b2011-10-03 03:20:16 +02001841 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 old_length = PyUnicode_WSTR_LENGTH(unicode);
1843 else
1844 old_length = PyUnicode_GET_LENGTH(unicode);
1845 if (old_length == length)
1846 return 0;
1847
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001848 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001849 _Py_INCREF_UNICODE_EMPTY();
1850 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001851 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001852 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001853 return 0;
1854 }
1855
Victor Stinner488fa492011-12-12 00:01:39 +01001856 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001857 PyObject *copy = resize_copy(unicode, length);
1858 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001859 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001860 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001861 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001862 }
1863
Victor Stinnerfe226c02011-10-03 03:52:20 +02001864 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001865 PyObject *new_unicode = resize_compact(unicode, length);
1866 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001867 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001868 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001869 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001870 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001871 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001875PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001876{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001877 PyObject *unicode;
1878 if (p_unicode == NULL) {
1879 PyErr_BadInternalCall();
1880 return -1;
1881 }
1882 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001883 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 {
1885 PyErr_BadInternalCall();
1886 return -1;
1887 }
1888 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001889}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001890
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001891/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001892
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001893 WARNING: The function doesn't copy the terminating null character and
1894 doesn't check the maximum character (may write a latin1 character in an
1895 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001896static void
1897unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1898 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001899{
1900 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1901 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001902 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001903
1904 switch (kind) {
1905 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001906 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001907#ifdef Py_DEBUG
1908 if (PyUnicode_IS_ASCII(unicode)) {
1909 Py_UCS4 maxchar = ucs1lib_find_max_char(
1910 (const Py_UCS1*)str,
1911 (const Py_UCS1*)str + len);
1912 assert(maxchar < 128);
1913 }
1914#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001915 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001916 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001917 }
1918 case PyUnicode_2BYTE_KIND: {
1919 Py_UCS2 *start = (Py_UCS2 *)data + index;
1920 Py_UCS2 *ucs2 = start;
1921 assert(index <= PyUnicode_GET_LENGTH(unicode));
1922
Victor Stinner184252a2012-06-16 02:57:41 +02001923 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001924 *ucs2 = (Py_UCS2)*str;
1925
1926 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001927 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001928 }
1929 default: {
1930 Py_UCS4 *start = (Py_UCS4 *)data + index;
1931 Py_UCS4 *ucs4 = start;
1932 assert(kind == PyUnicode_4BYTE_KIND);
1933 assert(index <= PyUnicode_GET_LENGTH(unicode));
1934
Victor Stinner184252a2012-06-16 02:57:41 +02001935 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001936 *ucs4 = (Py_UCS4)*str;
1937
1938 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001939 }
1940 }
1941}
1942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943static PyObject*
1944get_latin1_char(unsigned char ch)
1945{
Victor Stinnera464fc12011-10-02 20:39:30 +02001946 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001948 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001949 if (!unicode)
1950 return NULL;
1951 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001952 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 unicode_latin1[ch] = unicode;
1954 }
1955 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001956 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957}
1958
Victor Stinner985a82a2014-01-03 12:53:47 +01001959static PyObject*
1960unicode_char(Py_UCS4 ch)
1961{
1962 PyObject *unicode;
1963
1964 assert(ch <= MAX_UNICODE);
1965
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001966 if (ch < 256)
1967 return get_latin1_char(ch);
1968
Victor Stinner985a82a2014-01-03 12:53:47 +01001969 unicode = PyUnicode_New(1, ch);
1970 if (unicode == NULL)
1971 return NULL;
1972 switch (PyUnicode_KIND(unicode)) {
1973 case PyUnicode_1BYTE_KIND:
1974 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1975 break;
1976 case PyUnicode_2BYTE_KIND:
1977 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1978 break;
1979 default:
1980 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1981 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1982 }
1983 assert(_PyUnicode_CheckConsistency(unicode, 1));
1984 return unicode;
1985}
1986
Alexander Belopolsky40018472011-02-26 01:02:56 +00001987PyObject *
1988PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001989{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001990 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991 Py_UCS4 maxchar = 0;
1992 Py_ssize_t num_surrogates;
1993
1994 if (u == NULL)
1995 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001996
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001997 /* If the Unicode data is known at construction time, we can apply
1998 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002001 if (size == 0)
2002 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 /* Single character Unicode objects in the Latin-1 range are
2005 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002006 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 return get_latin1_char((unsigned char)*u);
2008
2009 /* If not empty and not single character, copy the Unicode data
2010 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002011 if (find_maxchar_surrogates(u, u + size,
2012 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 return NULL;
2014
Victor Stinner8faf8212011-12-08 22:14:11 +01002015 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002016 if (!unicode)
2017 return NULL;
2018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 switch (PyUnicode_KIND(unicode)) {
2020 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002021 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2023 break;
2024 case PyUnicode_2BYTE_KIND:
2025#if Py_UNICODE_SIZE == 2
2026 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2027#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002028 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2030#endif
2031 break;
2032 case PyUnicode_4BYTE_KIND:
2033#if SIZEOF_WCHAR_T == 2
2034 /* This is the only case which has to process surrogates, thus
2035 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002036 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037#else
2038 assert(num_surrogates == 0);
2039 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2040#endif
2041 break;
2042 default:
2043 assert(0 && "Impossible state");
2044 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002045
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002046 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002047}
2048
Alexander Belopolsky40018472011-02-26 01:02:56 +00002049PyObject *
2050PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002051{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002052 if (size < 0) {
2053 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002054 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002055 return NULL;
2056 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002057 if (u != NULL)
2058 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2059 else
2060 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002061}
2062
Alexander Belopolsky40018472011-02-26 01:02:56 +00002063PyObject *
2064PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002065{
2066 size_t size = strlen(u);
2067 if (size > PY_SSIZE_T_MAX) {
2068 PyErr_SetString(PyExc_OverflowError, "input too long");
2069 return NULL;
2070 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002071 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002072}
2073
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002074PyObject *
2075_PyUnicode_FromId(_Py_Identifier *id)
2076{
2077 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002078 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2079 strlen(id->string),
2080 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081 if (!id->object)
2082 return NULL;
2083 PyUnicode_InternInPlace(&id->object);
2084 assert(!id->next);
2085 id->next = static_strings;
2086 static_strings = id;
2087 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002088 return id->object;
2089}
2090
2091void
2092_PyUnicode_ClearStaticStrings()
2093{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002094 _Py_Identifier *tmp, *s = static_strings;
2095 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002096 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002097 tmp = s->next;
2098 s->next = NULL;
2099 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002100 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002101 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002102}
2103
Benjamin Peterson0df54292012-03-26 14:50:32 -04002104/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002105
Victor Stinnerd3f08822012-05-29 12:57:52 +02002106PyObject*
2107_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002108{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002109 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002110 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002111 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002112#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002113 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002114#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002115 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002116 }
Victor Stinner785938e2011-12-11 20:09:03 +01002117 unicode = PyUnicode_New(size, 127);
2118 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002119 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002120 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2121 assert(_PyUnicode_CheckConsistency(unicode, 1));
2122 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002123}
2124
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002125static Py_UCS4
2126kind_maxchar_limit(unsigned int kind)
2127{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002128 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002129 case PyUnicode_1BYTE_KIND:
2130 return 0x80;
2131 case PyUnicode_2BYTE_KIND:
2132 return 0x100;
2133 case PyUnicode_4BYTE_KIND:
2134 return 0x10000;
2135 default:
2136 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002137 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002138 }
2139}
2140
Victor Stinnere6abb482012-05-02 01:15:40 +02002141Py_LOCAL_INLINE(Py_UCS4)
2142align_maxchar(Py_UCS4 maxchar)
2143{
2144 if (maxchar <= 127)
2145 return 127;
2146 else if (maxchar <= 255)
2147 return 255;
2148 else if (maxchar <= 65535)
2149 return 65535;
2150 else
2151 return MAX_UNICODE;
2152}
2153
Victor Stinner702c7342011-10-05 13:50:52 +02002154static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002155_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002158 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002159
Serhiy Storchaka678db842013-01-26 12:16:36 +02002160 if (size == 0)
2161 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002162 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002163 if (size == 1)
2164 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002165
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002166 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002167 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002168 if (!res)
2169 return NULL;
2170 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002171 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002172 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002173}
2174
Victor Stinnere57b1c02011-09-28 22:20:48 +02002175static PyObject*
2176_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177{
2178 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002179 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002180
Serhiy Storchaka678db842013-01-26 12:16:36 +02002181 if (size == 0)
2182 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002183 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002184 if (size == 1)
2185 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002186
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002187 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002188 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002189 if (!res)
2190 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002191 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002193 else {
2194 _PyUnicode_CONVERT_BYTES(
2195 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2196 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002197 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return res;
2199}
2200
Victor Stinnere57b1c02011-09-28 22:20:48 +02002201static PyObject*
2202_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203{
2204 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002205 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002206
Serhiy Storchaka678db842013-01-26 12:16:36 +02002207 if (size == 0)
2208 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002209 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002210 if (size == 1)
2211 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002212
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002214 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 if (!res)
2216 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002217 if (max_char < 256)
2218 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2219 PyUnicode_1BYTE_DATA(res));
2220 else if (max_char < 0x10000)
2221 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2222 PyUnicode_2BYTE_DATA(res));
2223 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002225 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002226 return res;
2227}
2228
2229PyObject*
2230PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2231{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002232 if (size < 0) {
2233 PyErr_SetString(PyExc_ValueError, "size must be positive");
2234 return NULL;
2235 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002236 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002238 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002239 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002240 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002242 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002243 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002244 PyErr_SetString(PyExc_SystemError, "invalid kind");
2245 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247}
2248
Victor Stinnerece58de2012-04-23 23:36:38 +02002249Py_UCS4
2250_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2251{
2252 enum PyUnicode_Kind kind;
2253 void *startptr, *endptr;
2254
2255 assert(PyUnicode_IS_READY(unicode));
2256 assert(0 <= start);
2257 assert(end <= PyUnicode_GET_LENGTH(unicode));
2258 assert(start <= end);
2259
2260 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2261 return PyUnicode_MAX_CHAR_VALUE(unicode);
2262
2263 if (start == end)
2264 return 127;
2265
Victor Stinner94d558b2012-04-27 22:26:58 +02002266 if (PyUnicode_IS_ASCII(unicode))
2267 return 127;
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002270 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002271 endptr = (char *)startptr + end * kind;
2272 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002273 switch(kind) {
2274 case PyUnicode_1BYTE_KIND:
2275 return ucs1lib_find_max_char(startptr, endptr);
2276 case PyUnicode_2BYTE_KIND:
2277 return ucs2lib_find_max_char(startptr, endptr);
2278 case PyUnicode_4BYTE_KIND:
2279 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002280 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002281 assert(0);
2282 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002283 }
2284}
2285
Victor Stinner25a4b292011-10-06 12:31:55 +02002286/* Ensure that a string uses the most efficient storage, if it is not the
2287 case: create a new string with of the right kind. Write NULL into *p_unicode
2288 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002289static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002290unicode_adjust_maxchar(PyObject **p_unicode)
2291{
2292 PyObject *unicode, *copy;
2293 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002294 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002295 unsigned int kind;
2296
2297 assert(p_unicode != NULL);
2298 unicode = *p_unicode;
2299 assert(PyUnicode_IS_READY(unicode));
2300 if (PyUnicode_IS_ASCII(unicode))
2301 return;
2302
2303 len = PyUnicode_GET_LENGTH(unicode);
2304 kind = PyUnicode_KIND(unicode);
2305 if (kind == PyUnicode_1BYTE_KIND) {
2306 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002307 max_char = ucs1lib_find_max_char(u, u + len);
2308 if (max_char >= 128)
2309 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002310 }
2311 else if (kind == PyUnicode_2BYTE_KIND) {
2312 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 max_char = ucs2lib_find_max_char(u, u + len);
2314 if (max_char >= 256)
2315 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002316 }
2317 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002318 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002319 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002320 max_char = ucs4lib_find_max_char(u, u + len);
2321 if (max_char >= 0x10000)
2322 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002323 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002325 if (copy != NULL)
2326 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002327 Py_DECREF(unicode);
2328 *p_unicode = copy;
2329}
2330
Victor Stinner034f6cf2011-09-30 02:26:44 +02002331PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002332_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002333{
Victor Stinner87af4f22011-11-21 23:03:47 +01002334 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002335 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002336
Victor Stinner034f6cf2011-09-30 02:26:44 +02002337 if (!PyUnicode_Check(unicode)) {
2338 PyErr_BadInternalCall();
2339 return NULL;
2340 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002341 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002342 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002343
Victor Stinner87af4f22011-11-21 23:03:47 +01002344 length = PyUnicode_GET_LENGTH(unicode);
2345 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002346 if (!copy)
2347 return NULL;
2348 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2349
Victor Stinner87af4f22011-11-21 23:03:47 +01002350 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2351 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002352 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002353 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002354}
2355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356
Victor Stinnerbc603d12011-10-02 01:00:40 +02002357/* Widen Unicode objects to larger buffers. Don't write terminating null
2358 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002359
2360void*
2361_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2362{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002363 Py_ssize_t len;
2364 void *result;
2365 unsigned int skind;
2366
Benjamin Petersonbac79492012-01-14 13:34:47 -05002367 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002368 return NULL;
2369
2370 len = PyUnicode_GET_LENGTH(s);
2371 skind = PyUnicode_KIND(s);
2372 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002373 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374 return NULL;
2375 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002376 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002377 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002378 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002379 if (!result)
2380 return PyErr_NoMemory();
2381 assert(skind == PyUnicode_1BYTE_KIND);
2382 _PyUnicode_CONVERT_BYTES(
2383 Py_UCS1, Py_UCS2,
2384 PyUnicode_1BYTE_DATA(s),
2385 PyUnicode_1BYTE_DATA(s) + len,
2386 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002387 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002388 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002389 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002390 if (!result)
2391 return PyErr_NoMemory();
2392 if (skind == PyUnicode_2BYTE_KIND) {
2393 _PyUnicode_CONVERT_BYTES(
2394 Py_UCS2, Py_UCS4,
2395 PyUnicode_2BYTE_DATA(s),
2396 PyUnicode_2BYTE_DATA(s) + len,
2397 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002398 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002399 else {
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS4,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
2406 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002408 default:
2409 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002410 }
Victor Stinner01698042011-10-04 00:04:26 +02002411 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 return NULL;
2413}
2414
2415static Py_UCS4*
2416as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2417 int copy_null)
2418{
2419 int kind;
2420 void *data;
2421 Py_ssize_t len, targetlen;
2422 if (PyUnicode_READY(string) == -1)
2423 return NULL;
2424 kind = PyUnicode_KIND(string);
2425 data = PyUnicode_DATA(string);
2426 len = PyUnicode_GET_LENGTH(string);
2427 targetlen = len;
2428 if (copy_null)
2429 targetlen++;
2430 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002431 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432 if (!target) {
2433 PyErr_NoMemory();
2434 return NULL;
2435 }
2436 }
2437 else {
2438 if (targetsize < targetlen) {
2439 PyErr_Format(PyExc_SystemError,
2440 "string is longer than the buffer");
2441 if (copy_null && 0 < targetsize)
2442 target[0] = 0;
2443 return NULL;
2444 }
2445 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002446 if (kind == PyUnicode_1BYTE_KIND) {
2447 Py_UCS1 *start = (Py_UCS1 *) data;
2448 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002450 else if (kind == PyUnicode_2BYTE_KIND) {
2451 Py_UCS2 *start = (Py_UCS2 *) data;
2452 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2453 }
2454 else {
2455 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002458 if (copy_null)
2459 target[len] = 0;
2460 return target;
2461}
2462
2463Py_UCS4*
2464PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2465 int copy_null)
2466{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002467 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 PyErr_BadInternalCall();
2469 return NULL;
2470 }
2471 return as_ucs4(string, target, targetsize, copy_null);
2472}
2473
2474Py_UCS4*
2475PyUnicode_AsUCS4Copy(PyObject *string)
2476{
2477 return as_ucs4(string, NULL, 0, 1);
2478}
2479
2480#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002481
Alexander Belopolsky40018472011-02-26 01:02:56 +00002482PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002483PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002484{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002485 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002486 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002487 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002488 PyErr_BadInternalCall();
2489 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002490 }
2491
Martin v. Löwis790465f2008-04-05 20:41:37 +00002492 if (size == -1) {
2493 size = wcslen(w);
2494 }
2495
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002497}
2498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002499#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002500
Victor Stinner15a11362012-10-06 23:48:20 +02002501/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002502 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2503 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2504#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002505
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002506static int
2507unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2508 Py_ssize_t width, Py_ssize_t precision)
2509{
2510 Py_ssize_t length, fill, arglen;
2511 Py_UCS4 maxchar;
2512
2513 if (PyUnicode_READY(str) == -1)
2514 return -1;
2515
2516 length = PyUnicode_GET_LENGTH(str);
2517 if ((precision == -1 || precision >= length)
2518 && width <= length)
2519 return _PyUnicodeWriter_WriteStr(writer, str);
2520
2521 if (precision != -1)
2522 length = Py_MIN(precision, length);
2523
2524 arglen = Py_MAX(length, width);
2525 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2526 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2527 else
2528 maxchar = writer->maxchar;
2529
2530 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2531 return -1;
2532
2533 if (width > length) {
2534 fill = width - length;
2535 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2536 return -1;
2537 writer->pos += fill;
2538 }
2539
2540 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2541 str, 0, length);
2542 writer->pos += length;
2543 return 0;
2544}
2545
2546static int
2547unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2548 Py_ssize_t width, Py_ssize_t precision)
2549{
2550 /* UTF-8 */
2551 Py_ssize_t length;
2552 PyObject *unicode;
2553 int res;
2554
2555 length = strlen(str);
2556 if (precision != -1)
2557 length = Py_MIN(length, precision);
2558 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2559 if (unicode == NULL)
2560 return -1;
2561
2562 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2563 Py_DECREF(unicode);
2564 return res;
2565}
2566
Victor Stinner96865452011-03-01 23:44:09 +00002567static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002568unicode_fromformat_arg(_PyUnicodeWriter *writer,
2569 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002570{
Victor Stinnere215d962012-10-06 23:03:36 +02002571 const char *p;
2572 Py_ssize_t len;
2573 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002574 Py_ssize_t width;
2575 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002576 int longflag;
2577 int longlongflag;
2578 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002580
2581 p = f;
2582 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002583 zeropad = 0;
2584 if (*f == '0') {
2585 zeropad = 1;
2586 f++;
2587 }
Victor Stinner96865452011-03-01 23:44:09 +00002588
2589 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002590 width = -1;
2591 if (Py_ISDIGIT((unsigned)*f)) {
2592 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002593 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002594 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002596 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002597 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002598 return NULL;
2599 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002600 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002601 f++;
2602 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002603 }
2604 precision = -1;
2605 if (*f == '.') {
2606 f++;
2607 if (Py_ISDIGIT((unsigned)*f)) {
2608 precision = (*f - '0');
2609 f++;
2610 while (Py_ISDIGIT((unsigned)*f)) {
2611 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2612 PyErr_SetString(PyExc_ValueError,
2613 "precision too big");
2614 return NULL;
2615 }
2616 precision = (precision * 10) + (*f - '0');
2617 f++;
2618 }
2619 }
Victor Stinner96865452011-03-01 23:44:09 +00002620 if (*f == '%') {
2621 /* "%.3%s" => f points to "3" */
2622 f--;
2623 }
2624 }
2625 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002626 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002627 f--;
2628 }
Victor Stinner96865452011-03-01 23:44:09 +00002629
2630 /* Handle %ld, %lu, %lld and %llu. */
2631 longflag = 0;
2632 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002633 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002634 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002635 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002636 longflag = 1;
2637 ++f;
2638 }
Victor Stinner96865452011-03-01 23:44:09 +00002639 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002640 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002641 longlongflag = 1;
2642 f += 2;
2643 }
Victor Stinner96865452011-03-01 23:44:09 +00002644 }
2645 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002646 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002647 size_tflag = 1;
2648 ++f;
2649 }
Victor Stinnere215d962012-10-06 23:03:36 +02002650
2651 if (f[1] == '\0')
2652 writer->overallocate = 0;
2653
2654 switch (*f) {
2655 case 'c':
2656 {
2657 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002659 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002660 "character argument not in range(0x110000)");
2661 return NULL;
2662 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002663 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002664 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002665 break;
2666 }
2667
2668 case 'i':
2669 case 'd':
2670 case 'u':
2671 case 'x':
2672 {
2673 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002674 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002675 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002676
2677 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002678 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002679 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002680 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002681 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002682 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002683 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002684 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002685 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002686 va_arg(*vargs, size_t));
2687 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002688 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002689 va_arg(*vargs, unsigned int));
2690 }
2691 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002692 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002693 }
2694 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002695 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002696 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002697 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002698 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002699 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002700 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002701 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002702 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002703 va_arg(*vargs, Py_ssize_t));
2704 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002705 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002706 va_arg(*vargs, int));
2707 }
2708 assert(len >= 0);
2709
Victor Stinnere215d962012-10-06 23:03:36 +02002710 if (precision < len)
2711 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712
2713 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002714 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2715 return NULL;
2716
Victor Stinnere215d962012-10-06 23:03:36 +02002717 if (width > precision) {
2718 Py_UCS4 fillchar;
2719 fill = width - precision;
2720 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002721 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2722 return NULL;
2723 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002724 }
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002726 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002727 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2728 return NULL;
2729 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002730 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002731
Victor Stinner4a587072013-11-19 12:54:53 +01002732 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2733 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002734 break;
2735 }
2736
2737 case 'p':
2738 {
2739 char number[MAX_LONG_LONG_CHARS];
2740
2741 len = sprintf(number, "%p", va_arg(*vargs, void*));
2742 assert(len >= 0);
2743
2744 /* %p is ill-defined: ensure leading 0x. */
2745 if (number[1] == 'X')
2746 number[1] = 'x';
2747 else if (number[1] != 'x') {
2748 memmove(number + 2, number,
2749 strlen(number) + 1);
2750 number[0] = '0';
2751 number[1] = 'x';
2752 len += 2;
2753 }
2754
Victor Stinner4a587072013-11-19 12:54:53 +01002755 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002756 return NULL;
2757 break;
2758 }
2759
2760 case 's':
2761 {
2762 /* UTF-8 */
2763 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002764 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002765 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002766 break;
2767 }
2768
2769 case 'U':
2770 {
2771 PyObject *obj = va_arg(*vargs, PyObject *);
2772 assert(obj && _PyUnicode_CHECK(obj));
2773
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002774 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002775 return NULL;
2776 break;
2777 }
2778
2779 case 'V':
2780 {
2781 PyObject *obj = va_arg(*vargs, PyObject *);
2782 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002783 if (obj) {
2784 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002785 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002786 return NULL;
2787 }
2788 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002789 assert(str != NULL);
2790 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002791 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002792 }
2793 break;
2794 }
2795
2796 case 'S':
2797 {
2798 PyObject *obj = va_arg(*vargs, PyObject *);
2799 PyObject *str;
2800 assert(obj);
2801 str = PyObject_Str(obj);
2802 if (!str)
2803 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002804 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002805 Py_DECREF(str);
2806 return NULL;
2807 }
2808 Py_DECREF(str);
2809 break;
2810 }
2811
2812 case 'R':
2813 {
2814 PyObject *obj = va_arg(*vargs, PyObject *);
2815 PyObject *repr;
2816 assert(obj);
2817 repr = PyObject_Repr(obj);
2818 if (!repr)
2819 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002820 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002821 Py_DECREF(repr);
2822 return NULL;
2823 }
2824 Py_DECREF(repr);
2825 break;
2826 }
2827
2828 case 'A':
2829 {
2830 PyObject *obj = va_arg(*vargs, PyObject *);
2831 PyObject *ascii;
2832 assert(obj);
2833 ascii = PyObject_ASCII(obj);
2834 if (!ascii)
2835 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002836 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002837 Py_DECREF(ascii);
2838 return NULL;
2839 }
2840 Py_DECREF(ascii);
2841 break;
2842 }
2843
2844 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002845 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002846 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002847 break;
2848
2849 default:
2850 /* if we stumble upon an unknown formatting code, copy the rest
2851 of the format string to the output string. (we cannot just
2852 skip the code, since there's no way to know what's in the
2853 argument list) */
2854 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002855 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002856 return NULL;
2857 f = p+len;
2858 return f;
2859 }
2860
2861 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002862 return f;
2863}
2864
Walter Dörwaldd2034312007-05-18 16:29:38 +00002865PyObject *
2866PyUnicode_FromFormatV(const char *format, va_list vargs)
2867{
Victor Stinnere215d962012-10-06 23:03:36 +02002868 va_list vargs2;
2869 const char *f;
2870 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002871
Victor Stinner8f674cc2013-04-17 23:02:17 +02002872 _PyUnicodeWriter_Init(&writer);
2873 writer.min_length = strlen(format) + 100;
2874 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002875
2876 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2877 Copy it to be able to pass a reference to a subfunction. */
2878 Py_VA_COPY(vargs2, vargs);
2879
2880 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002881 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002882 f = unicode_fromformat_arg(&writer, f, &vargs2);
2883 if (f == NULL)
2884 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002886 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002887 const char *p;
2888 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002889
Victor Stinnere215d962012-10-06 23:03:36 +02002890 p = f;
2891 do
2892 {
2893 if ((unsigned char)*p > 127) {
2894 PyErr_Format(PyExc_ValueError,
2895 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2896 "string, got a non-ASCII byte: 0x%02x",
2897 (unsigned char)*p);
2898 return NULL;
2899 }
2900 p++;
2901 }
2902 while (*p != '\0' && *p != '%');
2903 len = p - f;
2904
2905 if (*p == '\0')
2906 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002907
2908 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002909 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002910
2911 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002912 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002913 }
Victor Stinnere215d962012-10-06 23:03:36 +02002914 return _PyUnicodeWriter_Finish(&writer);
2915
2916 fail:
2917 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002918 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002919}
2920
Walter Dörwaldd2034312007-05-18 16:29:38 +00002921PyObject *
2922PyUnicode_FromFormat(const char *format, ...)
2923{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002924 PyObject* ret;
2925 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002926
2927#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002928 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002929#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002931#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002932 ret = PyUnicode_FromFormatV(format, vargs);
2933 va_end(vargs);
2934 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002935}
2936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002937#ifdef HAVE_WCHAR_H
2938
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2940 convert a Unicode object to a wide character string.
2941
Victor Stinnerd88d9832011-09-06 02:00:05 +02002942 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002943 character) required to convert the unicode object. Ignore size argument.
2944
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002946 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002947 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002949unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002950 wchar_t *w,
2951 Py_ssize_t size)
2952{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002953 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002954 const wchar_t *wstr;
2955
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002956 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 if (wstr == NULL)
2958 return -1;
2959
Victor Stinner5593d8a2010-10-02 11:11:27 +00002960 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002961 if (size > res)
2962 size = res + 1;
2963 else
2964 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002965 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002966 return res;
2967 }
2968 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002969 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002970}
2971
2972Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002973PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002974 wchar_t *w,
2975 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002976{
2977 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 PyErr_BadInternalCall();
2979 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002980 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002981 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982}
2983
Victor Stinner137c34c2010-09-29 10:25:54 +00002984wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002985PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002986 Py_ssize_t *size)
2987{
2988 wchar_t* buffer;
2989 Py_ssize_t buflen;
2990
2991 if (unicode == NULL) {
2992 PyErr_BadInternalCall();
2993 return NULL;
2994 }
2995
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002996 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002997 if (buflen == -1)
2998 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002999 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003000 if (buffer == NULL) {
3001 PyErr_NoMemory();
3002 return NULL;
3003 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003004 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003005 if (buflen == -1) {
3006 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003007 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003008 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003009 if (size != NULL)
3010 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003011 return buffer;
3012}
3013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015
Alexander Belopolsky40018472011-02-26 01:02:56 +00003016PyObject *
3017PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003018{
Victor Stinner8faf8212011-12-08 22:14:11 +01003019 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 PyErr_SetString(PyExc_ValueError,
3021 "chr() arg not in range(0x110000)");
3022 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003023 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003024
Victor Stinner985a82a2014-01-03 12:53:47 +01003025 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003026}
3027
Alexander Belopolsky40018472011-02-26 01:02:56 +00003028PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003029PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003031 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003032 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003033 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003034 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003035 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 Py_INCREF(obj);
3037 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003038 }
3039 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003040 /* For a Unicode subtype that's not a Unicode object,
3041 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003042 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003043 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003044 PyErr_Format(PyExc_TypeError,
3045 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003046 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003047 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048}
3049
Alexander Belopolsky40018472011-02-26 01:02:56 +00003050PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003051PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003052 const char *encoding,
3053 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003054{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003055 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003057
Guido van Rossumd57fd912000-03-10 22:53:23 +00003058 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003059 PyErr_BadInternalCall();
3060 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003061 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003062
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003063 /* Decoding bytes objects is the most common case and should be fast */
3064 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003065 if (PyBytes_GET_SIZE(obj) == 0)
3066 _Py_RETURN_UNICODE_EMPTY();
3067 v = PyUnicode_Decode(
3068 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3069 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003070 return v;
3071 }
3072
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003073 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003074 PyErr_SetString(PyExc_TypeError,
3075 "decoding str is not supported");
3076 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003077 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003078
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003079 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3080 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3081 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003082 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003083 Py_TYPE(obj)->tp_name);
3084 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003085 }
Tim Petersced69f82003-09-16 20:30:58 +00003086
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003088 PyBuffer_Release(&buffer);
3089 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003091
Serhiy Storchaka05997252013-01-26 12:14:02 +02003092 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003093 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003094 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003095}
3096
Victor Stinner942889a2016-09-05 15:40:10 -07003097/* Normalize an encoding name: C implementation of
3098 encodings.normalize_encoding(). Return 1 on success, or 0 on error (encoding
3099 is longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003100int
3101_Py_normalize_encoding(const char *encoding,
3102 char *lower,
3103 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003104{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003105 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003106 char *l;
3107 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003108 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003109
Victor Stinner942889a2016-09-05 15:40:10 -07003110 assert(encoding != NULL);
3111
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003112 e = encoding;
3113 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003114 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003115 punct = 0;
3116 while (1) {
3117 char c = *e;
3118 if (c == 0) {
3119 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003120 }
Victor Stinner942889a2016-09-05 15:40:10 -07003121
3122 if (Py_ISALNUM(c) || c == '.') {
3123 if (punct && l != lower) {
3124 if (l == l_end) {
3125 return 0;
3126 }
3127 *l++ = '_';
3128 }
3129 punct = 0;
3130
3131 if (l == l_end) {
3132 return 0;
3133 }
3134 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003137 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003138 }
Victor Stinner942889a2016-09-05 15:40:10 -07003139
3140 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003141 }
3142 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003143 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003144}
3145
Alexander Belopolsky40018472011-02-26 01:02:56 +00003146PyObject *
3147PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003148 Py_ssize_t size,
3149 const char *encoding,
3150 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003151{
3152 PyObject *buffer = NULL, *unicode;
3153 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003154 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3155
3156 if (encoding == NULL) {
3157 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3158 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003159
Fred Drakee4315f52000-05-09 19:53:39 +00003160 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003161 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3162 char *lower = buflower;
3163
3164 /* Fast paths */
3165 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3166 lower += 3;
3167 if (*lower == '_') {
3168 /* Match "utf8" and "utf_8" */
3169 lower++;
3170 }
3171
3172 if (lower[0] == '8' && lower[1] == 0) {
3173 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3174 }
3175 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3176 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3177 }
3178 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3179 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3180 }
3181 }
3182 else {
3183 if (strcmp(lower, "ascii") == 0
3184 || strcmp(lower, "us_ascii") == 0) {
3185 return PyUnicode_DecodeASCII(s, size, errors);
3186 }
3187 #ifdef HAVE_MBCS
3188 else if (strcmp(lower, "mbcs") == 0) {
3189 return PyUnicode_DecodeMBCS(s, size, errors);
3190 }
3191 #endif
3192 else if (strcmp(lower, "latin1") == 0
3193 || strcmp(lower, "latin_1") == 0
3194 || strcmp(lower, "iso_8859_1") == 0
3195 || strcmp(lower, "iso8859_1") == 0) {
3196 return PyUnicode_DecodeLatin1(s, size, errors);
3197 }
3198 }
Victor Stinner37296e82010-06-10 13:36:23 +00003199 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200
3201 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003202 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003203 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003204 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003205 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206 if (buffer == NULL)
3207 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003208 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 if (unicode == NULL)
3210 goto onError;
3211 if (!PyUnicode_Check(unicode)) {
3212 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003213 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3214 "use codecs.decode() to decode to arbitrary types",
3215 encoding,
3216 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003217 Py_DECREF(unicode);
3218 goto onError;
3219 }
3220 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003221 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003222
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003224 Py_XDECREF(buffer);
3225 return NULL;
3226}
3227
Alexander Belopolsky40018472011-02-26 01:02:56 +00003228PyObject *
3229PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003230 const char *encoding,
3231 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003232{
3233 PyObject *v;
3234
3235 if (!PyUnicode_Check(unicode)) {
3236 PyErr_BadArgument();
3237 goto onError;
3238 }
3239
3240 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003241 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242
3243 /* Decode via the codec registry */
3244 v = PyCodec_Decode(unicode, encoding, errors);
3245 if (v == NULL)
3246 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003247 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003248
Benjamin Peterson29060642009-01-31 22:14:21 +00003249 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003250 return NULL;
3251}
3252
Alexander Belopolsky40018472011-02-26 01:02:56 +00003253PyObject *
3254PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003255 const char *encoding,
3256 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003257{
3258 PyObject *v;
3259
3260 if (!PyUnicode_Check(unicode)) {
3261 PyErr_BadArgument();
3262 goto onError;
3263 }
3264
3265 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003266 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003267
3268 /* Decode via the codec registry */
3269 v = PyCodec_Decode(unicode, encoding, errors);
3270 if (v == NULL)
3271 goto onError;
3272 if (!PyUnicode_Check(v)) {
3273 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003274 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3275 "use codecs.decode() to decode to arbitrary types",
3276 encoding,
3277 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278 Py_DECREF(v);
3279 goto onError;
3280 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003281 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003282
Benjamin Peterson29060642009-01-31 22:14:21 +00003283 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003284 return NULL;
3285}
3286
Alexander Belopolsky40018472011-02-26 01:02:56 +00003287PyObject *
3288PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003289 Py_ssize_t size,
3290 const char *encoding,
3291 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292{
3293 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003294
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295 unicode = PyUnicode_FromUnicode(s, size);
3296 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003297 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003298 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3299 Py_DECREF(unicode);
3300 return v;
3301}
3302
Alexander Belopolsky40018472011-02-26 01:02:56 +00003303PyObject *
3304PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003305 const char *encoding,
3306 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003307{
3308 PyObject *v;
3309
3310 if (!PyUnicode_Check(unicode)) {
3311 PyErr_BadArgument();
3312 goto onError;
3313 }
3314
3315 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003316 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317
3318 /* Encode via the codec registry */
3319 v = PyCodec_Encode(unicode, encoding, errors);
3320 if (v == NULL)
3321 goto onError;
3322 return v;
3323
Benjamin Peterson29060642009-01-31 22:14:21 +00003324 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003325 return NULL;
3326}
3327
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003328static size_t
3329wcstombs_errorpos(const wchar_t *wstr)
3330{
3331 size_t len;
3332#if SIZEOF_WCHAR_T == 2
3333 wchar_t buf[3];
3334#else
3335 wchar_t buf[2];
3336#endif
3337 char outbuf[MB_LEN_MAX];
3338 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003339
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003340#if SIZEOF_WCHAR_T == 2
3341 buf[2] = 0;
3342#else
3343 buf[1] = 0;
3344#endif
3345 start = wstr;
3346 while (*wstr != L'\0')
3347 {
3348 previous = wstr;
3349#if SIZEOF_WCHAR_T == 2
3350 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3351 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3352 {
3353 buf[0] = wstr[0];
3354 buf[1] = wstr[1];
3355 wstr += 2;
3356 }
3357 else {
3358 buf[0] = *wstr;
3359 buf[1] = 0;
3360 wstr++;
3361 }
3362#else
3363 buf[0] = *wstr;
3364 wstr++;
3365#endif
3366 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003367 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003368 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 }
3370
3371 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003372 return 0;
3373}
3374
Victor Stinner1b579672011-12-17 05:47:23 +01003375static int
3376locale_error_handler(const char *errors, int *surrogateescape)
3377{
Victor Stinner50149202015-09-22 00:26:54 +02003378 _Py_error_handler error_handler = get_error_handler(errors);
3379 switch (error_handler)
3380 {
3381 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003382 *surrogateescape = 0;
3383 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003384 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003385 *surrogateescape = 1;
3386 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003387 default:
3388 PyErr_Format(PyExc_ValueError,
3389 "only 'strict' and 'surrogateescape' error handlers "
3390 "are supported, not '%s'",
3391 errors);
3392 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003393 }
Victor Stinner1b579672011-12-17 05:47:23 +01003394}
3395
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003397PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398{
3399 Py_ssize_t wlen, wlen2;
3400 wchar_t *wstr;
3401 PyObject *bytes = NULL;
3402 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003403 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003404 PyObject *exc;
3405 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003406 int surrogateescape;
3407
3408 if (locale_error_handler(errors, &surrogateescape) < 0)
3409 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410
3411 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3412 if (wstr == NULL)
3413 return NULL;
3414
3415 wlen2 = wcslen(wstr);
3416 if (wlen2 != wlen) {
3417 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003418 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003419 return NULL;
3420 }
3421
3422 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003423 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424 char *str;
3425
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003426 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 if (str == NULL) {
3428 if (error_pos == (size_t)-1) {
3429 PyErr_NoMemory();
3430 PyMem_Free(wstr);
3431 return NULL;
3432 }
3433 else {
3434 goto encode_error;
3435 }
3436 }
3437 PyMem_Free(wstr);
3438
3439 bytes = PyBytes_FromString(str);
3440 PyMem_Free(str);
3441 }
3442 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003443 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003444 size_t len, len2;
3445
3446 len = wcstombs(NULL, wstr, 0);
3447 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003448 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 goto encode_error;
3450 }
3451
3452 bytes = PyBytes_FromStringAndSize(NULL, len);
3453 if (bytes == NULL) {
3454 PyMem_Free(wstr);
3455 return NULL;
3456 }
3457
3458 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3459 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003460 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003461 goto encode_error;
3462 }
3463 PyMem_Free(wstr);
3464 }
3465 return bytes;
3466
3467encode_error:
3468 errmsg = strerror(errno);
3469 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003470
3471 if (error_pos == (size_t)-1)
3472 error_pos = wcstombs_errorpos(wstr);
3473
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003474 PyMem_Free(wstr);
3475 Py_XDECREF(bytes);
3476
Victor Stinner2f197072011-12-17 07:08:30 +01003477 if (errmsg != NULL) {
3478 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003479 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003480 if (wstr != NULL) {
3481 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003482 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003483 } else
3484 errmsg = NULL;
3485 }
3486 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003487 reason = PyUnicode_FromString(
3488 "wcstombs() encountered an unencodable "
3489 "wide character");
3490 if (reason == NULL)
3491 return NULL;
3492
3493 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3494 "locale", unicode,
3495 (Py_ssize_t)error_pos,
3496 (Py_ssize_t)(error_pos+1),
3497 reason);
3498 Py_DECREF(reason);
3499 if (exc != NULL) {
3500 PyCodec_StrictErrors(exc);
3501 Py_XDECREF(exc);
3502 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003503 return NULL;
3504}
3505
Victor Stinnerad158722010-10-27 00:25:46 +00003506PyObject *
3507PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003508{
Victor Stinner99b95382011-07-04 14:23:54 +02003509#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003510 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003511#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003512 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003513#else
Victor Stinner793b5312011-04-27 00:24:21 +02003514 PyInterpreterState *interp = PyThreadState_GET()->interp;
3515 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3516 cannot use it to encode and decode filenames before it is loaded. Load
3517 the Python codec requires to encode at least its own filename. Use the C
3518 version of the locale codec until the codec registry is initialized and
3519 the Python codec is loaded.
3520
3521 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3522 cannot only rely on it: check also interp->fscodec_initialized for
3523 subinterpreters. */
3524 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003525 return PyUnicode_AsEncodedString(unicode,
3526 Py_FileSystemDefaultEncoding,
3527 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003528 }
3529 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003530 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003531 }
Victor Stinnerad158722010-10-27 00:25:46 +00003532#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003533}
3534
Alexander Belopolsky40018472011-02-26 01:02:56 +00003535PyObject *
3536PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003537 const char *encoding,
3538 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003539{
3540 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003541 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003542
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543 if (!PyUnicode_Check(unicode)) {
3544 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003545 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003546 }
Fred Drakee4315f52000-05-09 19:53:39 +00003547
Victor Stinner942889a2016-09-05 15:40:10 -07003548 if (encoding == NULL) {
3549 return _PyUnicode_AsUTF8String(unicode, errors);
3550 }
3551
Fred Drakee4315f52000-05-09 19:53:39 +00003552 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003553 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3554 char *lower = buflower;
3555
3556 /* Fast paths */
3557 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3558 lower += 3;
3559 if (*lower == '_') {
3560 /* Match "utf8" and "utf_8" */
3561 lower++;
3562 }
3563
3564 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003565 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003566 }
3567 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3568 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3569 }
3570 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3571 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3572 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003573 }
Victor Stinner942889a2016-09-05 15:40:10 -07003574 else {
3575 if (strcmp(lower, "ascii") == 0
3576 || strcmp(lower, "us_ascii") == 0) {
3577 return _PyUnicode_AsASCIIString(unicode, errors);
3578 }
Victor Stinner99b95382011-07-04 14:23:54 +02003579#ifdef HAVE_MBCS
Victor Stinner942889a2016-09-05 15:40:10 -07003580 else if (strcmp(lower, "mbcs") == 0) {
3581 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3582 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003583#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003584 else if (strcmp(lower, "latin1") == 0 ||
3585 strcmp(lower, "latin_1") == 0 ||
3586 strcmp(lower, "iso_8859_1") == 0 ||
3587 strcmp(lower, "iso8859_1") == 0) {
3588 return _PyUnicode_AsLatin1String(unicode, errors);
3589 }
3590 }
Victor Stinner37296e82010-06-10 13:36:23 +00003591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003592
3593 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003594 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003595 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003596 return NULL;
3597
3598 /* The normal path */
3599 if (PyBytes_Check(v))
3600 return v;
3601
3602 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003603 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003604 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003605 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003606
3607 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003608 "encoder %s returned bytearray instead of bytes; "
3609 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003610 encoding);
3611 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003612 Py_DECREF(v);
3613 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003614 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003615
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003616 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3617 Py_DECREF(v);
3618 return b;
3619 }
3620
3621 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003622 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3623 "use codecs.encode() to encode to arbitrary types",
3624 encoding,
3625 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003626 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003627 return NULL;
3628}
3629
Alexander Belopolsky40018472011-02-26 01:02:56 +00003630PyObject *
3631PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003632 const char *encoding,
3633 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003634{
3635 PyObject *v;
3636
3637 if (!PyUnicode_Check(unicode)) {
3638 PyErr_BadArgument();
3639 goto onError;
3640 }
3641
3642 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003643 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003644
3645 /* Encode via the codec registry */
3646 v = PyCodec_Encode(unicode, encoding, errors);
3647 if (v == NULL)
3648 goto onError;
3649 if (!PyUnicode_Check(v)) {
3650 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003651 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3652 "use codecs.encode() to encode to arbitrary types",
3653 encoding,
3654 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003655 Py_DECREF(v);
3656 goto onError;
3657 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003658 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003659
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661 return NULL;
3662}
3663
Victor Stinner2f197072011-12-17 07:08:30 +01003664static size_t
3665mbstowcs_errorpos(const char *str, size_t len)
3666{
3667#ifdef HAVE_MBRTOWC
3668 const char *start = str;
3669 mbstate_t mbs;
3670 size_t converted;
3671 wchar_t ch;
3672
3673 memset(&mbs, 0, sizeof mbs);
3674 while (len)
3675 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003676 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003677 if (converted == 0)
3678 /* Reached end of string */
3679 break;
3680 if (converted == (size_t)-1 || converted == (size_t)-2) {
3681 /* Conversion error or incomplete character */
3682 return str - start;
3683 }
3684 else {
3685 str += converted;
3686 len -= converted;
3687 }
3688 }
3689 /* failed to find the undecodable byte sequence */
3690 return 0;
3691#endif
3692 return 0;
3693}
3694
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003695PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003696PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003697 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003698{
3699 wchar_t smallbuf[256];
3700 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3701 wchar_t *wstr;
3702 size_t wlen, wlen2;
3703 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003704 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003705 size_t error_pos;
3706 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003707 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3708 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003709
3710 if (locale_error_handler(errors, &surrogateescape) < 0)
3711 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003712
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003713 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3714 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003715 return NULL;
3716 }
3717
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003718 if (surrogateescape) {
3719 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003720 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003721 if (wstr == NULL) {
3722 if (wlen == (size_t)-1)
3723 PyErr_NoMemory();
3724 else
3725 PyErr_SetFromErrno(PyExc_OSError);
3726 return NULL;
3727 }
3728
3729 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003730 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003731 }
3732 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003733 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003734#ifndef HAVE_BROKEN_MBSTOWCS
3735 wlen = mbstowcs(NULL, str, 0);
3736#else
3737 wlen = len;
3738#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003739 if (wlen == (size_t)-1)
3740 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003741 if (wlen+1 <= smallbuf_len) {
3742 wstr = smallbuf;
3743 }
3744 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003745 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003746 if (!wstr)
3747 return PyErr_NoMemory();
3748 }
3749
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003750 wlen2 = mbstowcs(wstr, str, wlen+1);
3751 if (wlen2 == (size_t)-1) {
3752 if (wstr != smallbuf)
3753 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003754 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003755 }
3756#ifdef HAVE_BROKEN_MBSTOWCS
3757 assert(wlen2 == wlen);
3758#endif
3759 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3760 if (wstr != smallbuf)
3761 PyMem_Free(wstr);
3762 }
3763 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003764
3765decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003766 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003767 errmsg = strerror(errno);
3768 assert(errmsg != NULL);
3769
3770 error_pos = mbstowcs_errorpos(str, len);
3771 if (errmsg != NULL) {
3772 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003773 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003774 if (wstr != NULL) {
3775 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003776 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003777 }
Victor Stinner2f197072011-12-17 07:08:30 +01003778 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003779 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003780 reason = PyUnicode_FromString(
3781 "mbstowcs() encountered an invalid multibyte sequence");
3782 if (reason == NULL)
3783 return NULL;
3784
3785 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3786 "locale", str, len,
3787 (Py_ssize_t)error_pos,
3788 (Py_ssize_t)(error_pos+1),
3789 reason);
3790 Py_DECREF(reason);
3791 if (exc != NULL) {
3792 PyCodec_StrictErrors(exc);
3793 Py_XDECREF(exc);
3794 }
3795 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003796}
3797
3798PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003799PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003800{
3801 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003802 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003803}
3804
3805
3806PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003807PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003808 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003809 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3810}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003811
Christian Heimes5894ba72007-11-04 11:43:14 +00003812PyObject*
3813PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3814{
Victor Stinner99b95382011-07-04 14:23:54 +02003815#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003816 return PyUnicode_DecodeMBCS(s, size, NULL);
3817#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003818 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003819#else
Victor Stinner793b5312011-04-27 00:24:21 +02003820 PyInterpreterState *interp = PyThreadState_GET()->interp;
3821 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3822 cannot use it to encode and decode filenames before it is loaded. Load
3823 the Python codec requires to encode at least its own filename. Use the C
3824 version of the locale codec until the codec registry is initialized and
3825 the Python codec is loaded.
3826
3827 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3828 cannot only rely on it: check also interp->fscodec_initialized for
3829 subinterpreters. */
3830 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003831 return PyUnicode_Decode(s, size,
3832 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003833 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003834 }
3835 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003836 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003837 }
Victor Stinnerad158722010-10-27 00:25:46 +00003838#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003839}
3840
Martin v. Löwis011e8422009-05-05 04:43:17 +00003841
3842int
3843PyUnicode_FSConverter(PyObject* arg, void* addr)
3844{
Brett Cannonec6ce872016-09-06 15:50:29 -07003845 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003846 PyObject *output = NULL;
3847 Py_ssize_t size;
3848 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003849 if (arg == NULL) {
3850 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003851 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003852 return 1;
3853 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003854 path = PyOS_FSPath(arg);
3855 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003856 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003857 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003858 if (PyBytes_Check(path)) {
3859 output = path;
3860 }
3861 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3862 output = PyUnicode_EncodeFSDefault(path);
3863 Py_DECREF(path);
3864 if (!output) {
3865 return 0;
3866 }
3867 assert(PyBytes_Check(output));
3868 }
3869
Victor Stinner0ea2a462010-04-30 00:22:08 +00003870 size = PyBytes_GET_SIZE(output);
3871 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003872 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003873 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003874 Py_DECREF(output);
3875 return 0;
3876 }
3877 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003878 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003879}
3880
3881
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003882int
3883PyUnicode_FSDecoder(PyObject* arg, void* addr)
3884{
Brett Cannona5711202016-09-06 19:36:01 -07003885 int is_buffer = 0;
3886 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003887 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003888 if (arg == NULL) {
3889 Py_DECREF(*(PyObject**)addr);
3890 return 1;
3891 }
Brett Cannona5711202016-09-06 19:36:01 -07003892
3893 is_buffer = PyObject_CheckBuffer(arg);
3894 if (!is_buffer) {
3895 path = PyOS_FSPath(arg);
3896 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003897 return 0;
3898 }
Brett Cannona5711202016-09-06 19:36:01 -07003899 }
3900 else {
3901 path = arg;
3902 Py_INCREF(arg);
3903 }
3904
3905 if (PyUnicode_Check(path)) {
3906 if (PyUnicode_READY(path) == -1) {
3907 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003908 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003909 }
3910 output = path;
3911 }
3912 else if (PyBytes_Check(path) || is_buffer) {
3913 PyObject *path_bytes = NULL;
3914
3915 if (!PyBytes_Check(path) &&
3916 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3917 "path should be string, bytes, or os.PathLike, not %.200s",
3918 Py_TYPE(arg)->tp_name)) {
3919 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003920 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003921 }
3922 path_bytes = PyBytes_FromObject(path);
3923 Py_DECREF(path);
3924 if (!path_bytes) {
3925 return 0;
3926 }
3927 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3928 PyBytes_GET_SIZE(path_bytes));
3929 Py_DECREF(path_bytes);
3930 if (!output) {
3931 return 0;
3932 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003933 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003934 else {
3935 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003936 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003937 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003938 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003939 return 0;
3940 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003941 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003942 Py_DECREF(output);
3943 return 0;
3944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003946 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003947 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003948 Py_DECREF(output);
3949 return 0;
3950 }
3951 *(PyObject**)addr = output;
3952 return Py_CLEANUP_SUPPORTED;
3953}
3954
3955
Martin v. Löwis5b222132007-06-10 09:51:05 +00003956char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003957PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003958{
Christian Heimesf3863112007-11-22 07:46:41 +00003959 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003960
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003961 if (!PyUnicode_Check(unicode)) {
3962 PyErr_BadArgument();
3963 return NULL;
3964 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003965 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003966 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003967
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003968 if (PyUnicode_UTF8(unicode) == NULL) {
3969 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003970 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971 if (bytes == NULL)
3972 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003973 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3974 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003975 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976 Py_DECREF(bytes);
3977 return NULL;
3978 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003979 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3980 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3981 PyBytes_AS_STRING(bytes),
3982 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003983 Py_DECREF(bytes);
3984 }
3985
3986 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003987 *psize = PyUnicode_UTF8_LENGTH(unicode);
3988 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003989}
3990
3991char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003994 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3995}
3996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003997Py_UNICODE *
3998PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3999{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004000 const unsigned char *one_byte;
4001#if SIZEOF_WCHAR_T == 4
4002 const Py_UCS2 *two_bytes;
4003#else
4004 const Py_UCS4 *four_bytes;
4005 const Py_UCS4 *ucs4_end;
4006 Py_ssize_t num_surrogates;
4007#endif
4008 wchar_t *w;
4009 wchar_t *wchar_end;
4010
4011 if (!PyUnicode_Check(unicode)) {
4012 PyErr_BadArgument();
4013 return NULL;
4014 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004015 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004016 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004017 assert(_PyUnicode_KIND(unicode) != 0);
4018 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004020 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004021#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004022 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4023 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 num_surrogates = 0;
4025
4026 for (; four_bytes < ucs4_end; ++four_bytes) {
4027 if (*four_bytes > 0xFFFF)
4028 ++num_surrogates;
4029 }
4030
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004031 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4032 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4033 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034 PyErr_NoMemory();
4035 return NULL;
4036 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004037 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004039 w = _PyUnicode_WSTR(unicode);
4040 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4041 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004042 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4043 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004044 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004045 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004046 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4047 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004048 }
4049 else
4050 *w = *four_bytes;
4051
4052 if (w > wchar_end) {
4053 assert(0 && "Miscalculated string end");
4054 }
4055 }
4056 *w = 0;
4057#else
4058 /* sizeof(wchar_t) == 4 */
4059 Py_FatalError("Impossible unicode object state, wstr and str "
4060 "should share memory already.");
4061 return NULL;
4062#endif
4063 }
4064 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004065 if ((size_t)_PyUnicode_LENGTH(unicode) >
4066 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4067 PyErr_NoMemory();
4068 return NULL;
4069 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004070 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4071 (_PyUnicode_LENGTH(unicode) + 1));
4072 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004073 PyErr_NoMemory();
4074 return NULL;
4075 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004076 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4077 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4078 w = _PyUnicode_WSTR(unicode);
4079 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004080
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004081 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4082 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004083 for (; w < wchar_end; ++one_byte, ++w)
4084 *w = *one_byte;
4085 /* null-terminate the wstr */
4086 *w = 0;
4087 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004088 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004089#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004090 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004091 for (; w < wchar_end; ++two_bytes, ++w)
4092 *w = *two_bytes;
4093 /* null-terminate the wstr */
4094 *w = 0;
4095#else
4096 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004097 PyObject_FREE(_PyUnicode_WSTR(unicode));
4098 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004099 Py_FatalError("Impossible unicode object state, wstr "
4100 "and str should share memory already.");
4101 return NULL;
4102#endif
4103 }
4104 else {
4105 assert(0 && "This should never happen.");
4106 }
4107 }
4108 }
4109 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004110 *size = PyUnicode_WSTR_LENGTH(unicode);
4111 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004112}
4113
Alexander Belopolsky40018472011-02-26 01:02:56 +00004114Py_UNICODE *
4115PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004117 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004118}
4119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004120
Alexander Belopolsky40018472011-02-26 01:02:56 +00004121Py_ssize_t
4122PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004123{
4124 if (!PyUnicode_Check(unicode)) {
4125 PyErr_BadArgument();
4126 goto onError;
4127 }
4128 return PyUnicode_GET_SIZE(unicode);
4129
Benjamin Peterson29060642009-01-31 22:14:21 +00004130 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131 return -1;
4132}
4133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004134Py_ssize_t
4135PyUnicode_GetLength(PyObject *unicode)
4136{
Victor Stinner07621332012-06-16 04:53:46 +02004137 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004138 PyErr_BadArgument();
4139 return -1;
4140 }
Victor Stinner07621332012-06-16 04:53:46 +02004141 if (PyUnicode_READY(unicode) == -1)
4142 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004143 return PyUnicode_GET_LENGTH(unicode);
4144}
4145
4146Py_UCS4
4147PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4148{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004149 void *data;
4150 int kind;
4151
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004152 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4153 PyErr_BadArgument();
4154 return (Py_UCS4)-1;
4155 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004156 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004157 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004158 return (Py_UCS4)-1;
4159 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004160 data = PyUnicode_DATA(unicode);
4161 kind = PyUnicode_KIND(unicode);
4162 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004163}
4164
4165int
4166PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4167{
4168 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004169 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004170 return -1;
4171 }
Victor Stinner488fa492011-12-12 00:01:39 +01004172 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004173 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004174 PyErr_SetString(PyExc_IndexError, "string index out of range");
4175 return -1;
4176 }
Victor Stinner488fa492011-12-12 00:01:39 +01004177 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004178 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004179 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4180 PyErr_SetString(PyExc_ValueError, "character out of range");
4181 return -1;
4182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004183 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4184 index, ch);
4185 return 0;
4186}
4187
Alexander Belopolsky40018472011-02-26 01:02:56 +00004188const char *
4189PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004190{
Victor Stinner42cb4622010-09-01 19:39:01 +00004191 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004192}
4193
Victor Stinner554f3f02010-06-16 23:33:54 +00004194/* create or adjust a UnicodeDecodeError */
4195static void
4196make_decode_exception(PyObject **exceptionObject,
4197 const char *encoding,
4198 const char *input, Py_ssize_t length,
4199 Py_ssize_t startpos, Py_ssize_t endpos,
4200 const char *reason)
4201{
4202 if (*exceptionObject == NULL) {
4203 *exceptionObject = PyUnicodeDecodeError_Create(
4204 encoding, input, length, startpos, endpos, reason);
4205 }
4206 else {
4207 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4208 goto onError;
4209 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4210 goto onError;
4211 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4212 goto onError;
4213 }
4214 return;
4215
4216onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004217 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004218}
4219
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004220#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004221/* error handling callback helper:
4222 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004223 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224 and adjust various state variables.
4225 return 0 on success, -1 on error
4226*/
4227
Alexander Belopolsky40018472011-02-26 01:02:56 +00004228static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004229unicode_decode_call_errorhandler_wchar(
4230 const char *errors, PyObject **errorHandler,
4231 const char *encoding, const char *reason,
4232 const char **input, const char **inend, Py_ssize_t *startinpos,
4233 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4234 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004235{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004236 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237
4238 PyObject *restuple = NULL;
4239 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004240 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004241 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004242 Py_ssize_t requiredsize;
4243 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004244 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004245 wchar_t *repwstr;
4246 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004247
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004248 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4249 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004250
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004251 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004252 *errorHandler = PyCodec_LookupError(errors);
4253 if (*errorHandler == NULL)
4254 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004255 }
4256
Victor Stinner554f3f02010-06-16 23:33:54 +00004257 make_decode_exception(exceptionObject,
4258 encoding,
4259 *input, *inend - *input,
4260 *startinpos, *endinpos,
4261 reason);
4262 if (*exceptionObject == NULL)
4263 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004264
4265 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4266 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004267 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004269 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004270 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004271 }
4272 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004273 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004274
4275 /* Copy back the bytes variables, which might have been modified by the
4276 callback */
4277 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4278 if (!inputobj)
4279 goto onError;
4280 if (!PyBytes_Check(inputobj)) {
4281 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4282 }
4283 *input = PyBytes_AS_STRING(inputobj);
4284 insize = PyBytes_GET_SIZE(inputobj);
4285 *inend = *input + insize;
4286 /* we can DECREF safely, as the exception has another reference,
4287 so the object won't go away. */
4288 Py_DECREF(inputobj);
4289
4290 if (newpos<0)
4291 newpos = insize+newpos;
4292 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004293 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004294 goto onError;
4295 }
4296
4297 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4298 if (repwstr == NULL)
4299 goto onError;
4300 /* need more space? (at least enough for what we
4301 have+the replacement+the rest of the string (starting
4302 at the new input position), so we won't have to check space
4303 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004304 requiredsize = *outpos;
4305 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4306 goto overflow;
4307 requiredsize += repwlen;
4308 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4309 goto overflow;
4310 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004311 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004312 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313 requiredsize = 2*outsize;
4314 if (unicode_resize(output, requiredsize) < 0)
4315 goto onError;
4316 }
4317 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4318 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004319 *endinpos = newpos;
4320 *inptr = *input + newpos;
4321
4322 /* we made it! */
4323 Py_XDECREF(restuple);
4324 return 0;
4325
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004326 overflow:
4327 PyErr_SetString(PyExc_OverflowError,
4328 "decoded result is too long for a Python string");
4329
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004330 onError:
4331 Py_XDECREF(restuple);
4332 return -1;
4333}
4334#endif /* HAVE_MBCS */
4335
4336static int
4337unicode_decode_call_errorhandler_writer(
4338 const char *errors, PyObject **errorHandler,
4339 const char *encoding, const char *reason,
4340 const char **input, const char **inend, Py_ssize_t *startinpos,
4341 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4342 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4343{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004344 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004345
4346 PyObject *restuple = NULL;
4347 PyObject *repunicode = NULL;
4348 Py_ssize_t insize;
4349 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004350 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004351 PyObject *inputobj = NULL;
4352
4353 if (*errorHandler == NULL) {
4354 *errorHandler = PyCodec_LookupError(errors);
4355 if (*errorHandler == NULL)
4356 goto onError;
4357 }
4358
4359 make_decode_exception(exceptionObject,
4360 encoding,
4361 *input, *inend - *input,
4362 *startinpos, *endinpos,
4363 reason);
4364 if (*exceptionObject == NULL)
4365 goto onError;
4366
4367 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4368 if (restuple == NULL)
4369 goto onError;
4370 if (!PyTuple_Check(restuple)) {
4371 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4372 goto onError;
4373 }
4374 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004376
4377 /* Copy back the bytes variables, which might have been modified by the
4378 callback */
4379 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4380 if (!inputobj)
4381 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004382 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004383 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004384 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004385 *input = PyBytes_AS_STRING(inputobj);
4386 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004387 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004388 /* we can DECREF safely, as the exception has another reference,
4389 so the object won't go away. */
4390 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004391
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004392 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004393 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004394 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004395 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004396 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004397 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004398
Victor Stinner8f674cc2013-04-17 23:02:17 +02004399 if (PyUnicode_READY(repunicode) < 0)
4400 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004401 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004402 if (replen > 1) {
4403 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004404 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004405 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4406 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4407 goto onError;
4408 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004409 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004410 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004411
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004412 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004413 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004414
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004415 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004416 Py_XDECREF(restuple);
4417 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004418
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004420 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004422}
4423
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004424/* --- UTF-7 Codec -------------------------------------------------------- */
4425
Antoine Pitrou244651a2009-05-04 18:56:13 +00004426/* See RFC2152 for details. We encode conservatively and decode liberally. */
4427
4428/* Three simple macros defining base-64. */
4429
4430/* Is c a base-64 character? */
4431
4432#define IS_BASE64(c) \
4433 (((c) >= 'A' && (c) <= 'Z') || \
4434 ((c) >= 'a' && (c) <= 'z') || \
4435 ((c) >= '0' && (c) <= '9') || \
4436 (c) == '+' || (c) == '/')
4437
4438/* given that c is a base-64 character, what is its base-64 value? */
4439
4440#define FROM_BASE64(c) \
4441 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4442 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4443 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4444 (c) == '+' ? 62 : 63)
4445
4446/* What is the base-64 character of the bottom 6 bits of n? */
4447
4448#define TO_BASE64(n) \
4449 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4450
4451/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4452 * decoded as itself. We are permissive on decoding; the only ASCII
4453 * byte not decoding to itself is the + which begins a base64
4454 * string. */
4455
4456#define DECODE_DIRECT(c) \
4457 ((c) <= 127 && (c) != '+')
4458
4459/* The UTF-7 encoder treats ASCII characters differently according to
4460 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4461 * the above). See RFC2152. This array identifies these different
4462 * sets:
4463 * 0 : "Set D"
4464 * alphanumeric and '(),-./:?
4465 * 1 : "Set O"
4466 * !"#$%&*;<=>@[]^_`{|}
4467 * 2 : "whitespace"
4468 * ht nl cr sp
4469 * 3 : special (must be base64 encoded)
4470 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4471 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472
Tim Petersced69f82003-09-16 20:30:58 +00004473static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004474char utf7_category[128] = {
4475/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4476 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4477/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4478 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4479/* sp ! " # $ % & ' ( ) * + , - . / */
4480 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4481/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4482 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4483/* @ A B C D E F G H I J K L M N O */
4484 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4485/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4486 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4487/* ` a b c d e f g h i j k l m n o */
4488 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4489/* p q r s t u v w x y z { | } ~ del */
4490 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004491};
4492
Antoine Pitrou244651a2009-05-04 18:56:13 +00004493/* ENCODE_DIRECT: this character should be encoded as itself. The
4494 * answer depends on whether we are encoding set O as itself, and also
4495 * on whether we are encoding whitespace as itself. RFC2152 makes it
4496 * clear that the answers to these questions vary between
4497 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004498
Antoine Pitrou244651a2009-05-04 18:56:13 +00004499#define ENCODE_DIRECT(c, directO, directWS) \
4500 ((c) < 128 && (c) > 0 && \
4501 ((utf7_category[(c)] == 0) || \
4502 (directWS && (utf7_category[(c)] == 2)) || \
4503 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504
Alexander Belopolsky40018472011-02-26 01:02:56 +00004505PyObject *
4506PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004507 Py_ssize_t size,
4508 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004509{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004510 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4511}
4512
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513/* The decoder. The only state we preserve is our read position,
4514 * i.e. how many characters we have consumed. So if we end in the
4515 * middle of a shift sequence we have to back off the read position
4516 * and the output to the beginning of the sequence, otherwise we lose
4517 * all the shift state (seen bits, number of bits seen, high
4518 * surrogate). */
4519
Alexander Belopolsky40018472011-02-26 01:02:56 +00004520PyObject *
4521PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004522 Py_ssize_t size,
4523 const char *errors,
4524 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004525{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004526 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004527 Py_ssize_t startinpos;
4528 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004529 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004530 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004531 const char *errmsg = "";
4532 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004533 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 unsigned int base64bits = 0;
4535 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004536 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004537 PyObject *errorHandler = NULL;
4538 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004539
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004540 if (size == 0) {
4541 if (consumed)
4542 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004543 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004544 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004546 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004547 _PyUnicodeWriter_Init(&writer);
4548 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004549
4550 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004551 e = s + size;
4552
4553 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004554 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004555 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004556 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004557
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558 if (inShift) { /* in a base-64 section */
4559 if (IS_BASE64(ch)) { /* consume a base-64 character */
4560 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4561 base64bits += 6;
4562 s++;
4563 if (base64bits >= 16) {
4564 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004565 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 base64bits -= 16;
4567 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004568 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 if (surrogate) {
4570 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004571 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4572 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004573 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004574 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004576 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 }
4578 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004579 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004580 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004582 }
4583 }
Victor Stinner551ac952011-11-29 22:58:13 +01004584 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 /* first surrogate */
4586 surrogate = outCh;
4587 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004589 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004590 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004591 }
4592 }
4593 }
4594 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004595 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 if (base64bits > 0) { /* left-over bits */
4597 if (base64bits >= 6) {
4598 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004599 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600 errmsg = "partial character in shift sequence";
4601 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004602 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004603 else {
4604 /* Some bits remain; they should be zero */
4605 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004606 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004607 errmsg = "non-zero padding bits in shift sequence";
4608 goto utf7Error;
4609 }
4610 }
4611 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004612 if (surrogate && DECODE_DIRECT(ch)) {
4613 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4614 goto onError;
4615 }
4616 surrogate = 0;
4617 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 /* '-' is absorbed; other terminating
4619 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004620 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004622 }
4623 }
4624 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004625 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004626 s++; /* consume '+' */
4627 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004628 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004629 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004630 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004631 }
4632 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004633 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004634 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004635 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004637 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004638 }
4639 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004640 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004641 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004642 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004643 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004644 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004645 else {
4646 startinpos = s-starts;
4647 s++;
4648 errmsg = "unexpected special character";
4649 goto utf7Error;
4650 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004651 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004652utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004653 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004654 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004655 errors, &errorHandler,
4656 "utf7", errmsg,
4657 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004658 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004659 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004660 }
4661
Antoine Pitrou244651a2009-05-04 18:56:13 +00004662 /* end of string */
4663
4664 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4665 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004666 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004667 if (surrogate ||
4668 (base64bits >= 6) ||
4669 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004670 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004671 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004672 errors, &errorHandler,
4673 "utf7", "unterminated shift sequence",
4674 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004675 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004676 goto onError;
4677 if (s < e)
4678 goto restart;
4679 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004680 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681
4682 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004683 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004684 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004685 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004686 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004687 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004688 writer.kind, writer.data, shiftOutStart);
4689 Py_XDECREF(errorHandler);
4690 Py_XDECREF(exc);
4691 _PyUnicodeWriter_Dealloc(&writer);
4692 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004693 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004694 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 }
4696 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004697 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004698 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004699 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004700
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004701 Py_XDECREF(errorHandler);
4702 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004703 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004704
Benjamin Peterson29060642009-01-31 22:14:21 +00004705 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004706 Py_XDECREF(errorHandler);
4707 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004708 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004709 return NULL;
4710}
4711
4712
Alexander Belopolsky40018472011-02-26 01:02:56 +00004713PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004714_PyUnicode_EncodeUTF7(PyObject *str,
4715 int base64SetO,
4716 int base64WhiteSpace,
4717 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004718{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004719 int kind;
4720 void *data;
4721 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004722 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004723 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004724 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004725 unsigned int base64bits = 0;
4726 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004727 char * out;
4728 char * start;
4729
Benjamin Petersonbac79492012-01-14 13:34:47 -05004730 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004731 return NULL;
4732 kind = PyUnicode_KIND(str);
4733 data = PyUnicode_DATA(str);
4734 len = PyUnicode_GET_LENGTH(str);
4735
4736 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004737 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004738
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004739 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004740 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004741 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004742 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004743 if (v == NULL)
4744 return NULL;
4745
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004746 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004747 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004748 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004749
Antoine Pitrou244651a2009-05-04 18:56:13 +00004750 if (inShift) {
4751 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4752 /* shifting out */
4753 if (base64bits) { /* output remaining bits */
4754 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4755 base64buffer = 0;
4756 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004757 }
4758 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004759 /* Characters not in the BASE64 set implicitly unshift the sequence
4760 so no '-' is required, except if the character is itself a '-' */
4761 if (IS_BASE64(ch) || ch == '-') {
4762 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004763 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004764 *out++ = (char) ch;
4765 }
4766 else {
4767 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004768 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004769 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004770 else { /* not in a shift sequence */
4771 if (ch == '+') {
4772 *out++ = '+';
4773 *out++ = '-';
4774 }
4775 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4776 *out++ = (char) ch;
4777 }
4778 else {
4779 *out++ = '+';
4780 inShift = 1;
4781 goto encode_char;
4782 }
4783 }
4784 continue;
4785encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004786 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004787 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004788
Antoine Pitrou244651a2009-05-04 18:56:13 +00004789 /* code first surrogate */
4790 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004791 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004792 while (base64bits >= 6) {
4793 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4794 base64bits -= 6;
4795 }
4796 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004797 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004798 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004799 base64bits += 16;
4800 base64buffer = (base64buffer << 16) | ch;
4801 while (base64bits >= 6) {
4802 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4803 base64bits -= 6;
4804 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004805 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004806 if (base64bits)
4807 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4808 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004809 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004810 if (_PyBytes_Resize(&v, out - start) < 0)
4811 return NULL;
4812 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004813}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004814PyObject *
4815PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4816 Py_ssize_t size,
4817 int base64SetO,
4818 int base64WhiteSpace,
4819 const char *errors)
4820{
4821 PyObject *result;
4822 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4823 if (tmp == NULL)
4824 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004825 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004826 base64WhiteSpace, errors);
4827 Py_DECREF(tmp);
4828 return result;
4829}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004830
Antoine Pitrou244651a2009-05-04 18:56:13 +00004831#undef IS_BASE64
4832#undef FROM_BASE64
4833#undef TO_BASE64
4834#undef DECODE_DIRECT
4835#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004836
Guido van Rossumd57fd912000-03-10 22:53:23 +00004837/* --- UTF-8 Codec -------------------------------------------------------- */
4838
Alexander Belopolsky40018472011-02-26 01:02:56 +00004839PyObject *
4840PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004841 Py_ssize_t size,
4842 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004843{
Walter Dörwald69652032004-09-07 20:24:22 +00004844 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4845}
4846
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847#include "stringlib/asciilib.h"
4848#include "stringlib/codecs.h"
4849#include "stringlib/undef.h"
4850
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004851#include "stringlib/ucs1lib.h"
4852#include "stringlib/codecs.h"
4853#include "stringlib/undef.h"
4854
4855#include "stringlib/ucs2lib.h"
4856#include "stringlib/codecs.h"
4857#include "stringlib/undef.h"
4858
4859#include "stringlib/ucs4lib.h"
4860#include "stringlib/codecs.h"
4861#include "stringlib/undef.h"
4862
Antoine Pitrouab868312009-01-10 15:40:25 +00004863/* Mask to quickly check whether a C 'long' contains a
4864 non-ASCII, UTF8-encoded char. */
4865#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004866# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004867#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004868# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004869#else
4870# error C 'long' size should be either 4 or 8!
4871#endif
4872
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004873static Py_ssize_t
4874ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004875{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004876 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004877 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004878
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004879 /*
4880 * Issue #17237: m68k is a bit different from most architectures in
4881 * that objects do not use "natural alignment" - for example, int and
4882 * long are only aligned at 2-byte boundaries. Therefore the assert()
4883 * won't work; also, tests have shown that skipping the "optimised
4884 * version" will even speed up m68k.
4885 */
4886#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004888 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4889 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004890 /* Fast path, see in STRINGLIB(utf8_decode) for
4891 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004892 /* Help allocation */
4893 const char *_p = p;
4894 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004895 while (_p < aligned_end) {
4896 unsigned long value = *(const unsigned long *) _p;
4897 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004898 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004899 *((unsigned long *)q) = value;
4900 _p += SIZEOF_LONG;
4901 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004902 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004903 p = _p;
4904 while (p < end) {
4905 if ((unsigned char)*p & 0x80)
4906 break;
4907 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004908 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004909 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004910 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004912#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004913 while (p < end) {
4914 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4915 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004916 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004917 /* Help allocation */
4918 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004919 while (_p < aligned_end) {
4920 unsigned long value = *(unsigned long *) _p;
4921 if (value & ASCII_CHAR_MASK)
4922 break;
4923 _p += SIZEOF_LONG;
4924 }
4925 p = _p;
4926 if (_p == end)
4927 break;
4928 }
4929 if ((unsigned char)*p & 0x80)
4930 break;
4931 ++p;
4932 }
4933 memcpy(dest, start, p - start);
4934 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004935}
Antoine Pitrouab868312009-01-10 15:40:25 +00004936
Victor Stinner785938e2011-12-11 20:09:03 +01004937PyObject *
4938PyUnicode_DecodeUTF8Stateful(const char *s,
4939 Py_ssize_t size,
4940 const char *errors,
4941 Py_ssize_t *consumed)
4942{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004943 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004944 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946
4947 Py_ssize_t startinpos;
4948 Py_ssize_t endinpos;
4949 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004950 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004952 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004953
4954 if (size == 0) {
4955 if (consumed)
4956 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004957 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004958 }
4959
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4961 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004962 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004963 *consumed = 1;
4964 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004965 }
4966
Victor Stinner8f674cc2013-04-17 23:02:17 +02004967 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004968 writer.min_length = size;
4969 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004970 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004971
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004972 writer.pos = ascii_decode(s, end, writer.data);
4973 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 while (s < end) {
4975 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004976 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004977
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004978 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004979 if (PyUnicode_IS_ASCII(writer.buffer))
4980 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004981 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004982 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 } else {
4986 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004988 }
4989
4990 switch (ch) {
4991 case 0:
4992 if (s == end || consumed)
4993 goto End;
4994 errmsg = "unexpected end of data";
4995 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004996 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004997 break;
4998 case 1:
4999 errmsg = "invalid start byte";
5000 startinpos = s - starts;
5001 endinpos = startinpos + 1;
5002 break;
5003 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005004 case 3:
5005 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 errmsg = "invalid continuation byte";
5007 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005008 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005009 break;
5010 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005011 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005012 goto onError;
5013 continue;
5014 }
5015
Victor Stinner1d65d912015-10-05 13:43:50 +02005016 if (error_handler == _Py_ERROR_UNKNOWN)
5017 error_handler = get_error_handler(errors);
5018
5019 switch (error_handler) {
5020 case _Py_ERROR_IGNORE:
5021 s += (endinpos - startinpos);
5022 break;
5023
5024 case _Py_ERROR_REPLACE:
5025 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5026 goto onError;
5027 s += (endinpos - startinpos);
5028 break;
5029
5030 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005031 {
5032 Py_ssize_t i;
5033
Victor Stinner1d65d912015-10-05 13:43:50 +02005034 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5035 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005036 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005037 ch = (Py_UCS4)(unsigned char)(starts[i]);
5038 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5039 ch + 0xdc00);
5040 writer.pos++;
5041 }
5042 s += (endinpos - startinpos);
5043 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005044 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005045
5046 default:
5047 if (unicode_decode_call_errorhandler_writer(
5048 errors, &error_handler_obj,
5049 "utf-8", errmsg,
5050 &starts, &end, &startinpos, &endinpos, &exc, &s,
5051 &writer))
5052 goto onError;
5053 }
Victor Stinner785938e2011-12-11 20:09:03 +01005054 }
5055
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005056End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005057 if (consumed)
5058 *consumed = s - starts;
5059
Victor Stinner1d65d912015-10-05 13:43:50 +02005060 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005061 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005062 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005063
5064onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005065 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005066 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005067 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005068 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005069}
5070
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005071#ifdef __APPLE__
5072
5073/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005074 used to decode the command line arguments on Mac OS X.
5075
5076 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005077 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005078
5079wchar_t*
5080_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5081{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005082 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005083 wchar_t *unicode;
5084 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005085
5086 /* Note: size will always be longer than the resulting Unicode
5087 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005088 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005089 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005090 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005091 if (!unicode)
5092 return NULL;
5093
5094 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005095 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005096 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005098 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005099#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005100 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005101#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005102 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005103#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005104 if (ch > 0xFF) {
5105#if SIZEOF_WCHAR_T == 4
5106 assert(0);
5107#else
5108 assert(Py_UNICODE_IS_SURROGATE(ch));
5109 /* compute and append the two surrogates: */
5110 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5111 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5112#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005113 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005114 else {
5115 if (!ch && s == e)
5116 break;
5117 /* surrogateescape */
5118 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5119 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005120 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005121 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005122 return unicode;
5123}
5124
5125#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005127/* Primary internal function which creates utf8 encoded bytes objects.
5128
5129 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005130 and allocate exactly as much space needed at the end. Else allocate the
5131 maximum possible needed (4 result bytes per Unicode character), and return
5132 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005133*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005134PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005135_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005136{
Victor Stinner6099a032011-12-18 14:22:26 +01005137 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005138 void *data;
5139 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005141 if (!PyUnicode_Check(unicode)) {
5142 PyErr_BadArgument();
5143 return NULL;
5144 }
5145
5146 if (PyUnicode_READY(unicode) == -1)
5147 return NULL;
5148
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005149 if (PyUnicode_UTF8(unicode))
5150 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5151 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005152
5153 kind = PyUnicode_KIND(unicode);
5154 data = PyUnicode_DATA(unicode);
5155 size = PyUnicode_GET_LENGTH(unicode);
5156
Benjamin Petersonead6b532011-12-20 17:23:42 -06005157 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005158 default:
5159 assert(0);
5160 case PyUnicode_1BYTE_KIND:
5161 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5162 assert(!PyUnicode_IS_ASCII(unicode));
5163 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5164 case PyUnicode_2BYTE_KIND:
5165 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5166 case PyUnicode_4BYTE_KIND:
5167 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005168 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005169}
5170
Alexander Belopolsky40018472011-02-26 01:02:56 +00005171PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005172PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5173 Py_ssize_t size,
5174 const char *errors)
5175{
5176 PyObject *v, *unicode;
5177
5178 unicode = PyUnicode_FromUnicode(s, size);
5179 if (unicode == NULL)
5180 return NULL;
5181 v = _PyUnicode_AsUTF8String(unicode, errors);
5182 Py_DECREF(unicode);
5183 return v;
5184}
5185
5186PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005187PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005188{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005189 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005190}
5191
Walter Dörwald41980ca2007-08-16 21:55:45 +00005192/* --- UTF-32 Codec ------------------------------------------------------- */
5193
5194PyObject *
5195PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005196 Py_ssize_t size,
5197 const char *errors,
5198 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005199{
5200 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5201}
5202
5203PyObject *
5204PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005205 Py_ssize_t size,
5206 const char *errors,
5207 int *byteorder,
5208 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005209{
5210 const char *starts = s;
5211 Py_ssize_t startinpos;
5212 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005213 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005214 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005215 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005216 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005218 PyObject *errorHandler = NULL;
5219 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005220
Walter Dörwald41980ca2007-08-16 21:55:45 +00005221 q = (unsigned char *)s;
5222 e = q + size;
5223
5224 if (byteorder)
5225 bo = *byteorder;
5226
5227 /* Check for BOM marks (U+FEFF) in the input and adjust current
5228 byte order setting accordingly. In native mode, the leading BOM
5229 mark is skipped, in all other modes, it is copied to the output
5230 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005231 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005232 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005233 if (bom == 0x0000FEFF) {
5234 bo = -1;
5235 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005237 else if (bom == 0xFFFE0000) {
5238 bo = 1;
5239 q += 4;
5240 }
5241 if (byteorder)
5242 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005243 }
5244
Victor Stinnere64322e2012-10-30 23:12:47 +01005245 if (q == e) {
5246 if (consumed)
5247 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005248 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249 }
5250
Victor Stinnere64322e2012-10-30 23:12:47 +01005251#ifdef WORDS_BIGENDIAN
5252 le = bo < 0;
5253#else
5254 le = bo <= 0;
5255#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005256 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005257
Victor Stinner8f674cc2013-04-17 23:02:17 +02005258 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005259 writer.min_length = (e - q + 3) / 4;
5260 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005261 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005262
Victor Stinnere64322e2012-10-30 23:12:47 +01005263 while (1) {
5264 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005265 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005266
Victor Stinnere64322e2012-10-30 23:12:47 +01005267 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005268 enum PyUnicode_Kind kind = writer.kind;
5269 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005270 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005271 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005272 if (le) {
5273 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005274 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005275 if (ch > maxch)
5276 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005277 if (kind != PyUnicode_1BYTE_KIND &&
5278 Py_UNICODE_IS_SURROGATE(ch))
5279 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005280 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005281 q += 4;
5282 } while (q <= last);
5283 }
5284 else {
5285 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005286 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005287 if (ch > maxch)
5288 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005289 if (kind != PyUnicode_1BYTE_KIND &&
5290 Py_UNICODE_IS_SURROGATE(ch))
5291 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005292 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005293 q += 4;
5294 } while (q <= last);
5295 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005296 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005297 }
5298
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005299 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005300 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005301 startinpos = ((const char *)q) - starts;
5302 endinpos = startinpos + 4;
5303 }
5304 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005305 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005307 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005308 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005309 startinpos = ((const char *)q) - starts;
5310 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005311 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005312 else {
5313 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005314 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005315 goto onError;
5316 q += 4;
5317 continue;
5318 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005319 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 startinpos = ((const char *)q) - starts;
5321 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005322 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005323
5324 /* The remaining input chars are ignored if the callback
5325 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005326 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005328 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005330 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005332 }
5333
Walter Dörwald41980ca2007-08-16 21:55:45 +00005334 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005335 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005336
Walter Dörwald41980ca2007-08-16 21:55:45 +00005337 Py_XDECREF(errorHandler);
5338 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005339 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005340
Benjamin Peterson29060642009-01-31 22:14:21 +00005341 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005342 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343 Py_XDECREF(errorHandler);
5344 Py_XDECREF(exc);
5345 return NULL;
5346}
5347
5348PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005349_PyUnicode_EncodeUTF32(PyObject *str,
5350 const char *errors,
5351 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005352{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005353 enum PyUnicode_Kind kind;
5354 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005355 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005356 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005357 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005358#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005359 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005360#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005361 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005362#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005363 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005364 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005365 PyObject *errorHandler = NULL;
5366 PyObject *exc = NULL;
5367 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005368
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005369 if (!PyUnicode_Check(str)) {
5370 PyErr_BadArgument();
5371 return NULL;
5372 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005373 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005374 return NULL;
5375 kind = PyUnicode_KIND(str);
5376 data = PyUnicode_DATA(str);
5377 len = PyUnicode_GET_LENGTH(str);
5378
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005379 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005380 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005381 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005382 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005383 if (v == NULL)
5384 return NULL;
5385
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005386 /* output buffer is 4-bytes aligned */
5387 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005388 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005389 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005391 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005392 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005393
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005394 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005395 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005396 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005397 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005398 else
5399 encoding = "utf-32";
5400
5401 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5403 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404 }
5405
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005406 pos = 0;
5407 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005408 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005409
5410 if (kind == PyUnicode_2BYTE_KIND) {
5411 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5412 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005413 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005414 else {
5415 assert(kind == PyUnicode_4BYTE_KIND);
5416 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5417 &out, native_ordering);
5418 }
5419 if (pos == len)
5420 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005421
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005422 rep = unicode_encode_call_errorhandler(
5423 errors, &errorHandler,
5424 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005426 if (!rep)
5427 goto error;
5428
5429 if (PyBytes_Check(rep)) {
5430 repsize = PyBytes_GET_SIZE(rep);
5431 if (repsize & 3) {
5432 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005433 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005434 "surrogates not allowed");
5435 goto error;
5436 }
5437 moreunits = repsize / 4;
5438 }
5439 else {
5440 assert(PyUnicode_Check(rep));
5441 if (PyUnicode_READY(rep) < 0)
5442 goto error;
5443 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5444 if (!PyUnicode_IS_ASCII(rep)) {
5445 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005446 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005447 "surrogates not allowed");
5448 goto error;
5449 }
5450 }
5451
5452 /* four bytes are reserved for each surrogate */
5453 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005454 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005455 Py_ssize_t morebytes = 4 * (moreunits - 1);
5456 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5457 /* integer overflow */
5458 PyErr_NoMemory();
5459 goto error;
5460 }
5461 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5462 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005463 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 }
5465
5466 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005467 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5468 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005471 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5472 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005473 }
5474
5475 Py_CLEAR(rep);
5476 }
5477
5478 /* Cut back to size actually needed. This is necessary for, for example,
5479 encoding of a string containing isolated surrogates and the 'ignore'
5480 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005481 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005482 if (nsize != PyBytes_GET_SIZE(v))
5483 _PyBytes_Resize(&v, nsize);
5484 Py_XDECREF(errorHandler);
5485 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005486 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005487 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005488 error:
5489 Py_XDECREF(rep);
5490 Py_XDECREF(errorHandler);
5491 Py_XDECREF(exc);
5492 Py_XDECREF(v);
5493 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005494}
5495
Alexander Belopolsky40018472011-02-26 01:02:56 +00005496PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005497PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5498 Py_ssize_t size,
5499 const char *errors,
5500 int byteorder)
5501{
5502 PyObject *result;
5503 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5504 if (tmp == NULL)
5505 return NULL;
5506 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5507 Py_DECREF(tmp);
5508 return result;
5509}
5510
5511PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005512PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005513{
Victor Stinnerb960b342011-11-20 19:12:52 +01005514 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005515}
5516
Guido van Rossumd57fd912000-03-10 22:53:23 +00005517/* --- UTF-16 Codec ------------------------------------------------------- */
5518
Tim Peters772747b2001-08-09 22:21:55 +00005519PyObject *
5520PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005521 Py_ssize_t size,
5522 const char *errors,
5523 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524{
Walter Dörwald69652032004-09-07 20:24:22 +00005525 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5526}
5527
5528PyObject *
5529PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005530 Py_ssize_t size,
5531 const char *errors,
5532 int *byteorder,
5533 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005534{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005535 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005536 Py_ssize_t startinpos;
5537 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005538 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005539 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005540 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005541 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005542 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005543 PyObject *errorHandler = NULL;
5544 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005545 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546
Tim Peters772747b2001-08-09 22:21:55 +00005547 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005548 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005549
5550 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005551 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005553 /* Check for BOM marks (U+FEFF) in the input and adjust current
5554 byte order setting accordingly. In native mode, the leading BOM
5555 mark is skipped, in all other modes, it is copied to the output
5556 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005557 if (bo == 0 && size >= 2) {
5558 const Py_UCS4 bom = (q[1] << 8) | q[0];
5559 if (bom == 0xFEFF) {
5560 q += 2;
5561 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005562 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005563 else if (bom == 0xFFFE) {
5564 q += 2;
5565 bo = 1;
5566 }
5567 if (byteorder)
5568 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005569 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005570
Antoine Pitrou63065d72012-05-15 23:48:04 +02005571 if (q == e) {
5572 if (consumed)
5573 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005574 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005575 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005576
Christian Heimes743e0cd2012-10-17 23:52:17 +02005577#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005578 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005579 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005580#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005582 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005583#endif
Tim Peters772747b2001-08-09 22:21:55 +00005584
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 /* Note: size will always be longer than the resulting Unicode
5586 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005587 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005588 writer.min_length = (e - q + 1) / 2;
5589 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005590 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591
Antoine Pitrou63065d72012-05-15 23:48:04 +02005592 while (1) {
5593 Py_UCS4 ch = 0;
5594 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005595 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005596 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005597 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005598 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005599 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 native_ordering);
5601 else
5602 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005603 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604 native_ordering);
5605 } else if (kind == PyUnicode_2BYTE_KIND) {
5606 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005607 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005608 native_ordering);
5609 } else {
5610 assert(kind == PyUnicode_4BYTE_KIND);
5611 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005612 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005614 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005615 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005616
Antoine Pitrou63065d72012-05-15 23:48:04 +02005617 switch (ch)
5618 {
5619 case 0:
5620 /* remaining byte at the end? (size should be even) */
5621 if (q == e || consumed)
5622 goto End;
5623 errmsg = "truncated data";
5624 startinpos = ((const char *)q) - starts;
5625 endinpos = ((const char *)e) - starts;
5626 break;
5627 /* The remaining input chars are ignored if the callback
5628 chooses to skip the input */
5629 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005630 q -= 2;
5631 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005632 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005633 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005634 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005635 endinpos = ((const char *)e) - starts;
5636 break;
5637 case 2:
5638 errmsg = "illegal encoding";
5639 startinpos = ((const char *)q) - 2 - starts;
5640 endinpos = startinpos + 2;
5641 break;
5642 case 3:
5643 errmsg = "illegal UTF-16 surrogate";
5644 startinpos = ((const char *)q) - 4 - starts;
5645 endinpos = startinpos + 2;
5646 break;
5647 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005648 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005649 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005650 continue;
5651 }
5652
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005653 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005654 errors,
5655 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005656 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005657 &starts,
5658 (const char **)&e,
5659 &startinpos,
5660 &endinpos,
5661 &exc,
5662 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005663 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665 }
5666
Antoine Pitrou63065d72012-05-15 23:48:04 +02005667End:
Walter Dörwald69652032004-09-07 20:24:22 +00005668 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005669 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005670
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005671 Py_XDECREF(errorHandler);
5672 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005673 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674
Benjamin Peterson29060642009-01-31 22:14:21 +00005675 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005676 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005677 Py_XDECREF(errorHandler);
5678 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679 return NULL;
5680}
5681
Tim Peters772747b2001-08-09 22:21:55 +00005682PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005683_PyUnicode_EncodeUTF16(PyObject *str,
5684 const char *errors,
5685 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005687 enum PyUnicode_Kind kind;
5688 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005689 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005690 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005691 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005692 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005693#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005694 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005695#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005696 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005697#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005698 const char *encoding;
5699 Py_ssize_t nsize, pos;
5700 PyObject *errorHandler = NULL;
5701 PyObject *exc = NULL;
5702 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005703
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005704 if (!PyUnicode_Check(str)) {
5705 PyErr_BadArgument();
5706 return NULL;
5707 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005708 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005709 return NULL;
5710 kind = PyUnicode_KIND(str);
5711 data = PyUnicode_DATA(str);
5712 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005713
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005714 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005715 if (kind == PyUnicode_4BYTE_KIND) {
5716 const Py_UCS4 *in = (const Py_UCS4 *)data;
5717 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005718 while (in < end) {
5719 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005720 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005721 }
5722 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005723 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005724 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005725 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005726 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005727 nsize = len + pairs + (byteorder == 0);
5728 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005729 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005731 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005733 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005734 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005735 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005736 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005737 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005738 }
5739 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005740 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005741 }
Tim Peters772747b2001-08-09 22:21:55 +00005742
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005743 if (kind == PyUnicode_1BYTE_KIND) {
5744 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5745 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005746 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005747
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005748 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005749 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005750 }
5751 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005752 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005753 }
5754 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005755 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005756 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757
5758 pos = 0;
5759 while (pos < len) {
5760 Py_ssize_t repsize, moreunits;
5761
5762 if (kind == PyUnicode_2BYTE_KIND) {
5763 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5764 &out, native_ordering);
5765 }
5766 else {
5767 assert(kind == PyUnicode_4BYTE_KIND);
5768 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5769 &out, native_ordering);
5770 }
5771 if (pos == len)
5772 break;
5773
5774 rep = unicode_encode_call_errorhandler(
5775 errors, &errorHandler,
5776 encoding, "surrogates not allowed",
5777 str, &exc, pos, pos + 1, &pos);
5778 if (!rep)
5779 goto error;
5780
5781 if (PyBytes_Check(rep)) {
5782 repsize = PyBytes_GET_SIZE(rep);
5783 if (repsize & 1) {
5784 raise_encode_exception(&exc, encoding,
5785 str, pos - 1, pos,
5786 "surrogates not allowed");
5787 goto error;
5788 }
5789 moreunits = repsize / 2;
5790 }
5791 else {
5792 assert(PyUnicode_Check(rep));
5793 if (PyUnicode_READY(rep) < 0)
5794 goto error;
5795 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5796 if (!PyUnicode_IS_ASCII(rep)) {
5797 raise_encode_exception(&exc, encoding,
5798 str, pos - 1, pos,
5799 "surrogates not allowed");
5800 goto error;
5801 }
5802 }
5803
5804 /* two bytes are reserved for each surrogate */
5805 if (moreunits > 1) {
5806 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5807 Py_ssize_t morebytes = 2 * (moreunits - 1);
5808 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5809 /* integer overflow */
5810 PyErr_NoMemory();
5811 goto error;
5812 }
5813 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5814 goto error;
5815 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5816 }
5817
5818 if (PyBytes_Check(rep)) {
5819 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5820 out += moreunits;
5821 } else /* rep is unicode */ {
5822 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5823 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5824 &out, native_ordering);
5825 }
5826
5827 Py_CLEAR(rep);
5828 }
5829
5830 /* Cut back to size actually needed. This is necessary for, for example,
5831 encoding of a string containing isolated surrogates and the 'ignore' handler
5832 is used. */
5833 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5834 if (nsize != PyBytes_GET_SIZE(v))
5835 _PyBytes_Resize(&v, nsize);
5836 Py_XDECREF(errorHandler);
5837 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005838 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005839 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005840 error:
5841 Py_XDECREF(rep);
5842 Py_XDECREF(errorHandler);
5843 Py_XDECREF(exc);
5844 Py_XDECREF(v);
5845 return NULL;
5846#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005847}
5848
Alexander Belopolsky40018472011-02-26 01:02:56 +00005849PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005850PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5851 Py_ssize_t size,
5852 const char *errors,
5853 int byteorder)
5854{
5855 PyObject *result;
5856 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5857 if (tmp == NULL)
5858 return NULL;
5859 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5860 Py_DECREF(tmp);
5861 return result;
5862}
5863
5864PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005865PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005867 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868}
5869
5870/* --- Unicode Escape Codec ----------------------------------------------- */
5871
Fredrik Lundh06d12682001-01-24 07:59:11 +00005872static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005873
Alexander Belopolsky40018472011-02-26 01:02:56 +00005874PyObject *
5875PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005876 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005877 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005880 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005882 PyObject *errorHandler = NULL;
5883 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005884
Victor Stinner62ec3312016-09-06 17:04:34 -07005885 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005886 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005887 }
5888 /* Escaped strings will always be longer than the resulting
5889 Unicode string, so we start with size here and then reduce the
5890 length after conversion to the true value.
5891 (but if the error callback returns a long replacement string
5892 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005893 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005894 writer.min_length = size;
5895 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5896 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005897 }
5898
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899 end = s + size;
5900 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005901 unsigned char c = (unsigned char) *s++;
5902 Py_UCS4 ch;
5903 int count;
5904 Py_ssize_t startinpos;
5905 Py_ssize_t endinpos;
5906 const char *message;
5907
5908#define WRITE_ASCII_CHAR(ch) \
5909 do { \
5910 assert(ch <= 127); \
5911 assert(writer.pos < writer.size); \
5912 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5913 } while(0)
5914
5915#define WRITE_CHAR(ch) \
5916 do { \
5917 if (ch <= writer.maxchar) { \
5918 assert(writer.pos < writer.size); \
5919 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5920 } \
5921 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5922 goto onError; \
5923 } \
5924 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925
5926 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005927 if (c != '\\') {
5928 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 continue;
5930 }
5931
Victor Stinner62ec3312016-09-06 17:04:34 -07005932 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005934 if (s >= end) {
5935 message = "\\ at end of string";
5936 goto error;
5937 }
5938 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005939
Victor Stinner62ec3312016-09-06 17:04:34 -07005940 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005941 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005944 case '\n': continue;
5945 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5946 case '\'': WRITE_ASCII_CHAR('\''); continue;
5947 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5948 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005949 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005950 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5951 case 't': WRITE_ASCII_CHAR('\t'); continue;
5952 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5953 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005954 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005955 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005956 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005957 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 case '0': case '1': case '2': case '3':
5961 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005962 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005963 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 ch = (ch<<3) + *s++ - '0';
5965 if (s < end && '0' <= *s && *s <= '7') {
5966 ch = (ch<<3) + *s++ - '0';
5967 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005969 WRITE_CHAR(ch);
5970 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
Benjamin Peterson29060642009-01-31 22:14:21 +00005972 /* hex escapes */
5973 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005975 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005976 message = "truncated \\xXX escape";
5977 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978
Benjamin Peterson29060642009-01-31 22:14:21 +00005979 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005981 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005982 message = "truncated \\uXXXX escape";
5983 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005986 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005987 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005988 message = "truncated \\UXXXXXXXX escape";
5989 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005991 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005992 ch <<= 4;
5993 if (c >= '0' && c <= '9') {
5994 ch += c - '0';
5995 }
5996 else if (c >= 'a' && c <= 'f') {
5997 ch += c - ('a' - 10);
5998 }
5999 else if (c >= 'A' && c <= 'F') {
6000 ch += c - ('A' - 10);
6001 }
6002 else {
6003 break;
6004 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006005 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006006 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006007 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006008 }
6009
6010 /* when we get here, ch is a 32-bit unicode character */
6011 if (ch > MAX_UNICODE) {
6012 message = "illegal Unicode character";
6013 goto error;
6014 }
6015
6016 WRITE_CHAR(ch);
6017 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006018
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006020 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006021 if (ucnhash_CAPI == NULL) {
6022 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006023 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6024 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006025 if (ucnhash_CAPI == NULL) {
6026 PyErr_SetString(
6027 PyExc_UnicodeError,
6028 "\\N escapes not supported (can't load unicodedata module)"
6029 );
6030 goto onError;
6031 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006032 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006033
6034 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006036 const char *start = ++s;
6037 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006038 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006039 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006040 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006041 namelen = s - start;
6042 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006044 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006045 ch = 0xffffffff; /* in case 'getcode' messes up */
6046 if (namelen <= INT_MAX &&
6047 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6048 &ch, 0)) {
6049 assert(ch <= MAX_UNICODE);
6050 WRITE_CHAR(ch);
6051 continue;
6052 }
6053 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 }
6055 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006056 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057
6058 default:
Victor Stinner62ec3312016-09-06 17:04:34 -07006059 WRITE_ASCII_CHAR('\\');
6060 WRITE_CHAR(c);
6061 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006063
6064 error:
6065 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006066 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006067 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006068 errors, &errorHandler,
6069 "unicodeescape", message,
6070 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006072 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 }
6074 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6075 goto onError;
6076 }
6077
6078#undef WRITE_ASCII_CHAR
6079#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006081
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006082 Py_XDECREF(errorHandler);
6083 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006084 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006085
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006087 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 Py_XDECREF(errorHandler);
6089 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090 return NULL;
6091}
6092
6093/* Return a Unicode-Escape string version of the Unicode object.
6094
6095 If quotes is true, the string is enclosed in u"" or u'' quotes as
6096 appropriate.
6097
6098*/
6099
Alexander Belopolsky40018472011-02-26 01:02:56 +00006100PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006101PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006103 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006104 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006105 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006106 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006107 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006108 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109
Ezio Melottie7f90372012-10-05 03:33:31 +03006110 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006111 escape.
6112
Ezio Melottie7f90372012-10-05 03:33:31 +03006113 For UCS1 strings it's '\xxx', 4 bytes per source character.
6114 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6115 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006116 */
6117
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006118 if (!PyUnicode_Check(unicode)) {
6119 PyErr_BadArgument();
6120 return NULL;
6121 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006122 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006123 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006124 }
Victor Stinner358af132015-10-12 22:36:57 +02006125
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006127 if (len == 0) {
6128 return PyBytes_FromStringAndSize(NULL, 0);
6129 }
6130
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006131 kind = PyUnicode_KIND(unicode);
6132 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006133 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6134 bytes, and 1 byte characters 4. */
6135 expandsize = kind * 2 + 2;
6136 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6137 return PyErr_NoMemory();
6138 }
6139 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6140 if (repr == NULL) {
6141 return NULL;
6142 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143
Victor Stinner62ec3312016-09-06 17:04:34 -07006144 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006146 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006147
Victor Stinner62ec3312016-09-06 17:04:34 -07006148 /* U+0000-U+00ff range */
6149 if (ch < 0x100) {
6150 if (ch >= ' ' && ch < 127) {
6151 if (ch != '\\') {
6152 /* Copy printable US ASCII as-is */
6153 *p++ = (char) ch;
6154 }
6155 /* Escape backslashes */
6156 else {
6157 *p++ = '\\';
6158 *p++ = '\\';
6159 }
6160 }
Victor Stinner358af132015-10-12 22:36:57 +02006161
Victor Stinner62ec3312016-09-06 17:04:34 -07006162 /* Map special whitespace to '\t', \n', '\r' */
6163 else if (ch == '\t') {
6164 *p++ = '\\';
6165 *p++ = 't';
6166 }
6167 else if (ch == '\n') {
6168 *p++ = '\\';
6169 *p++ = 'n';
6170 }
6171 else if (ch == '\r') {
6172 *p++ = '\\';
6173 *p++ = 'r';
6174 }
6175
6176 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6177 else {
6178 *p++ = '\\';
6179 *p++ = 'x';
6180 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6181 *p++ = Py_hexdigits[ch & 0x000F];
6182 }
Tim Petersced69f82003-09-16 20:30:58 +00006183 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006184 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6185 else if (ch < 0x10000) {
6186 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 *p++ = '\\';
6188 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006189 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6190 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6191 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6192 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006194 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6195 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006196
Victor Stinner62ec3312016-09-06 17:04:34 -07006197 /* Make sure that the first two digits are zero */
6198 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006199 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006200 *p++ = 'U';
6201 *p++ = '0';
6202 *p++ = '0';
6203 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6204 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6205 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6206 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6207 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6208 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006209 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006210 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 assert(p - PyBytes_AS_STRING(repr) > 0);
6213 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6214 return NULL;
6215 }
6216 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217}
6218
Alexander Belopolsky40018472011-02-26 01:02:56 +00006219PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006220PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6221 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006223 PyObject *result;
6224 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006225 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006226 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006227 }
6228
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229 result = PyUnicode_AsUnicodeEscapeString(tmp);
6230 Py_DECREF(tmp);
6231 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232}
6233
6234/* --- Raw Unicode Escape Codec ------------------------------------------- */
6235
Alexander Belopolsky40018472011-02-26 01:02:56 +00006236PyObject *
6237PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006238 Py_ssize_t size,
6239 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006241 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006242 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006244 PyObject *errorHandler = NULL;
6245 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006246
Victor Stinner62ec3312016-09-06 17:04:34 -07006247 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006248 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006250
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251 /* Escaped strings will always be longer than the resulting
6252 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006253 length after conversion to the true value. (But decoding error
6254 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006255 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006256 writer.min_length = size;
6257 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6258 goto onError;
6259 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006260
Guido van Rossumd57fd912000-03-10 22:53:23 +00006261 end = s + size;
6262 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006263 unsigned char c = (unsigned char) *s++;
6264 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006265 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006266 Py_ssize_t startinpos;
6267 Py_ssize_t endinpos;
6268 const char *message;
6269
6270#define WRITE_CHAR(ch) \
6271 do { \
6272 if (ch <= writer.maxchar) { \
6273 assert(writer.pos < writer.size); \
6274 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6275 } \
6276 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6277 goto onError; \
6278 } \
6279 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006280
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006282 if (c != '\\' || s >= end) {
6283 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006284 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006285 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006286
Victor Stinner62ec3312016-09-06 17:04:34 -07006287 c = (unsigned char) *s++;
6288 if (c == 'u') {
6289 count = 4;
6290 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006292 else if (c == 'U') {
6293 count = 8;
6294 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006295 }
6296 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006297 assert(writer.pos < writer.size);
6298 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6299 WRITE_CHAR(c);
6300 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006301 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006302 startinpos = s - starts - 2;
6303
6304 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6305 for (ch = 0; count && s < end; ++s, --count) {
6306 c = (unsigned char)*s;
6307 ch <<= 4;
6308 if (c >= '0' && c <= '9') {
6309 ch += c - '0';
6310 }
6311 else if (c >= 'a' && c <= 'f') {
6312 ch += c - ('a' - 10);
6313 }
6314 else if (c >= 'A' && c <= 'F') {
6315 ch += c - ('A' - 10);
6316 }
6317 else {
6318 break;
6319 }
6320 }
6321 if (!count) {
6322 if (ch <= MAX_UNICODE) {
6323 WRITE_CHAR(ch);
6324 continue;
6325 }
6326 message = "\\Uxxxxxxxx out of range";
6327 }
6328
6329 endinpos = s-starts;
6330 writer.min_length = end - s + writer.pos;
6331 if (unicode_decode_call_errorhandler_writer(
6332 errors, &errorHandler,
6333 "rawunicodeescape", message,
6334 &starts, &end, &startinpos, &endinpos, &exc, &s,
6335 &writer)) {
6336 goto onError;
6337 }
6338 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6339 goto onError;
6340 }
6341
6342#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006344 Py_XDECREF(errorHandler);
6345 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006346 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006347
Benjamin Peterson29060642009-01-31 22:14:21 +00006348 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006349 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006350 Py_XDECREF(errorHandler);
6351 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006352 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006353
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354}
6355
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006356
Alexander Belopolsky40018472011-02-26 01:02:56 +00006357PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006358PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006359{
Victor Stinner62ec3312016-09-06 17:04:34 -07006360 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006361 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006362 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006363 int kind;
6364 void *data;
6365 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006366
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006367 if (!PyUnicode_Check(unicode)) {
6368 PyErr_BadArgument();
6369 return NULL;
6370 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006371 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006372 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006374 kind = PyUnicode_KIND(unicode);
6375 data = PyUnicode_DATA(unicode);
6376 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 if (kind == PyUnicode_1BYTE_KIND) {
6378 return PyBytes_FromStringAndSize(data, len);
6379 }
Victor Stinner0e368262011-11-10 20:12:49 +01006380
Victor Stinner62ec3312016-09-06 17:04:34 -07006381 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6382 bytes, and 1 byte characters 4. */
6383 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006384
Victor Stinner62ec3312016-09-06 17:04:34 -07006385 if (len > PY_SSIZE_T_MAX / expandsize) {
6386 return PyErr_NoMemory();
6387 }
6388 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6389 if (repr == NULL) {
6390 return NULL;
6391 }
6392 if (len == 0) {
6393 return repr;
6394 }
6395
6396 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397 for (pos = 0; pos < len; pos++) {
6398 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006399
Victor Stinner62ec3312016-09-06 17:04:34 -07006400 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6401 if (ch < 0x100) {
6402 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006403 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006404 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6405 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406 *p++ = '\\';
6407 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006408 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6409 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6410 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6411 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006412 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006413 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6414 else {
6415 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6416 *p++ = '\\';
6417 *p++ = 'U';
6418 *p++ = '0';
6419 *p++ = '0';
6420 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6421 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6422 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6423 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6424 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6425 *p++ = Py_hexdigits[ch & 15];
6426 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006428
Victor Stinner62ec3312016-09-06 17:04:34 -07006429 assert(p > PyBytes_AS_STRING(repr));
6430 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6431 return NULL;
6432 }
6433 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434}
6435
Alexander Belopolsky40018472011-02-26 01:02:56 +00006436PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006437PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6438 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006440 PyObject *result;
6441 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6442 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006443 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006444 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6445 Py_DECREF(tmp);
6446 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006447}
6448
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006449/* --- Unicode Internal Codec ------------------------------------------- */
6450
Alexander Belopolsky40018472011-02-26 01:02:56 +00006451PyObject *
6452_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006453 Py_ssize_t size,
6454 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006455{
6456 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006457 Py_ssize_t startinpos;
6458 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006459 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006460 const char *end;
6461 const char *reason;
6462 PyObject *errorHandler = NULL;
6463 PyObject *exc = NULL;
6464
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006465 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006466 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006467 1))
6468 return NULL;
6469
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006470 if (size == 0)
6471 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006472
Victor Stinner8f674cc2013-04-17 23:02:17 +02006473 _PyUnicodeWriter_Init(&writer);
6474 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6475 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006477 }
6478 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006479
Victor Stinner8f674cc2013-04-17 23:02:17 +02006480 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006481 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006482 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006483 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006484 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006485 endinpos = end-starts;
6486 reason = "truncated input";
6487 goto error;
6488 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006489 /* We copy the raw representation one byte at a time because the
6490 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006491 ((char *) &uch)[0] = s[0];
6492 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006493#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006494 ((char *) &uch)[2] = s[2];
6495 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006496#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006497 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006498#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006499 /* We have to sanity check the raw data, otherwise doom looms for
6500 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006501 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006502 endinpos = s - starts + Py_UNICODE_SIZE;
6503 reason = "illegal code point (> 0x10FFFF)";
6504 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006505 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006506#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006507 s += Py_UNICODE_SIZE;
6508#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006509 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006510 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006511 Py_UNICODE uch2;
6512 ((char *) &uch2)[0] = s[0];
6513 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006514 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006515 {
Victor Stinner551ac952011-11-29 22:58:13 +01006516 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006517 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006518 }
6519 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006520#endif
6521
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006522 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006523 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006524 continue;
6525
6526 error:
6527 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006528 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006529 errors, &errorHandler,
6530 "unicode_internal", reason,
6531 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006532 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006533 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006534 }
6535
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006536 Py_XDECREF(errorHandler);
6537 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006538 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006539
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006541 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006542 Py_XDECREF(errorHandler);
6543 Py_XDECREF(exc);
6544 return NULL;
6545}
6546
Guido van Rossumd57fd912000-03-10 22:53:23 +00006547/* --- Latin-1 Codec ------------------------------------------------------ */
6548
Alexander Belopolsky40018472011-02-26 01:02:56 +00006549PyObject *
6550PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006551 Py_ssize_t size,
6552 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006553{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006554 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006555 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556}
6557
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006558/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006559static void
6560make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006561 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006562 PyObject *unicode,
6563 Py_ssize_t startpos, Py_ssize_t endpos,
6564 const char *reason)
6565{
6566 if (*exceptionObject == NULL) {
6567 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006568 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006569 encoding, unicode, startpos, endpos, reason);
6570 }
6571 else {
6572 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6573 goto onError;
6574 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6575 goto onError;
6576 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6577 goto onError;
6578 return;
6579 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006580 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006581 }
6582}
6583
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006585static void
6586raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006587 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006588 PyObject *unicode,
6589 Py_ssize_t startpos, Py_ssize_t endpos,
6590 const char *reason)
6591{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006592 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006593 encoding, unicode, startpos, endpos, reason);
6594 if (*exceptionObject != NULL)
6595 PyCodec_StrictErrors(*exceptionObject);
6596}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006597
6598/* error handling callback helper:
6599 build arguments, call the callback and check the arguments,
6600 put the result into newpos and return the replacement string, which
6601 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006602static PyObject *
6603unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006604 PyObject **errorHandler,
6605 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006606 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006607 Py_ssize_t startpos, Py_ssize_t endpos,
6608 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006610 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006612 PyObject *restuple;
6613 PyObject *resunicode;
6614
6615 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006617 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006619 }
6620
Benjamin Petersonbac79492012-01-14 13:34:47 -05006621 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622 return NULL;
6623 len = PyUnicode_GET_LENGTH(unicode);
6624
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006625 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006626 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006627 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006629
6630 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006632 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006635 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 Py_DECREF(restuple);
6637 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006639 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 &resunicode, newpos)) {
6641 Py_DECREF(restuple);
6642 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006643 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006644 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6645 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6646 Py_DECREF(restuple);
6647 return NULL;
6648 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006650 *newpos = len + *newpos;
6651 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006652 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 Py_DECREF(restuple);
6654 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006655 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 Py_INCREF(resunicode);
6657 Py_DECREF(restuple);
6658 return resunicode;
6659}
6660
Alexander Belopolsky40018472011-02-26 01:02:56 +00006661static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006663 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006664 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006665{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006666 /* input state */
6667 Py_ssize_t pos=0, size;
6668 int kind;
6669 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670 /* pointer into the output */
6671 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006672 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6673 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006674 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006676 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006677 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006678 /* output object */
6679 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680
Benjamin Petersonbac79492012-01-14 13:34:47 -05006681 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006682 return NULL;
6683 size = PyUnicode_GET_LENGTH(unicode);
6684 kind = PyUnicode_KIND(unicode);
6685 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686 /* allocate enough for a simple encoding without
6687 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006688 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006689 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006690
6691 _PyBytesWriter_Init(&writer);
6692 str = _PyBytesWriter_Alloc(&writer, size);
6693 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006694 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006696 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006697 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698
Benjamin Peterson29060642009-01-31 22:14:21 +00006699 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006700 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006702 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006703 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006704 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006706 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006709 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006710 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006711
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006712 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006714
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006715 /* Only overallocate the buffer if it's not the last write */
6716 writer.overallocate = (collend < size);
6717
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006719 if (error_handler == _Py_ERROR_UNKNOWN)
6720 error_handler = get_error_handler(errors);
6721
6722 switch (error_handler) {
6723 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006724 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006726
6727 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006728 memset(str, '?', collend - collstart);
6729 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006730 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006731 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006732 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 break;
Victor Stinner50149202015-09-22 00:26:54 +02006734
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006735 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006736 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006737 writer.min_size -= (collend - collstart);
6738 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006739 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006740 if (str == NULL)
6741 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006742 pos = collend;
6743 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006744
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006745 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006746 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006747 writer.min_size -= (collend - collstart);
6748 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006749 unicode, collstart, collend);
6750 if (str == NULL)
6751 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 break;
Victor Stinner50149202015-09-22 00:26:54 +02006754
Victor Stinnerc3713e92015-09-29 12:32:13 +02006755 case _Py_ERROR_SURROGATEESCAPE:
6756 for (i = collstart; i < collend; ++i) {
6757 ch = PyUnicode_READ(kind, data, i);
6758 if (ch < 0xdc80 || 0xdcff < ch) {
6759 /* Not a UTF-8b surrogate */
6760 break;
6761 }
6762 *str++ = (char)(ch - 0xdc00);
6763 ++pos;
6764 }
6765 if (i >= collend)
6766 break;
6767 collstart = pos;
6768 assert(collstart != collend);
6769 /* fallback to general error handling */
6770
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006772 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6773 encoding, reason, unicode, &exc,
6774 collstart, collend, &newpos);
6775 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006777
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006778 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006779 writer.min_size -= 1;
6780
Victor Stinner6bd525b2015-10-09 13:10:05 +02006781 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006782 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006783 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006784 PyBytes_AS_STRING(rep),
6785 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006786 if (str == NULL)
6787 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006788 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006789 else {
6790 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006791
Victor Stinner6bd525b2015-10-09 13:10:05 +02006792 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006794
6795 if (PyUnicode_IS_ASCII(rep)) {
6796 /* Fast path: all characters are smaller than limit */
6797 assert(limit >= 128);
6798 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6799 str = _PyBytesWriter_WriteBytes(&writer, str,
6800 PyUnicode_DATA(rep),
6801 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006803 else {
6804 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6805
6806 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6807 if (str == NULL)
6808 goto onError;
6809
6810 /* check if there is anything unencodable in the
6811 replacement and copy it to the output */
6812 for (i = 0; repsize-->0; ++i, ++str) {
6813 ch = PyUnicode_READ_CHAR(rep, i);
6814 if (ch >= limit) {
6815 raise_encode_exception(&exc, encoding, unicode,
6816 pos, pos+1, reason);
6817 goto onError;
6818 }
6819 *str = (char)ch;
6820 }
6821 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006823 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006824 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006825 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006826
6827 /* If overallocation was disabled, ensure that it was the last
6828 write. Otherwise, we missed an optimization */
6829 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006830 }
6831 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006832
Victor Stinner50149202015-09-22 00:26:54 +02006833 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006834 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006835 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006836
6837 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006838 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006839 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006840 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006841 Py_XDECREF(exc);
6842 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006843}
6844
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006846PyObject *
6847PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006848 Py_ssize_t size,
6849 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006850{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006851 PyObject *result;
6852 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6853 if (unicode == NULL)
6854 return NULL;
6855 result = unicode_encode_ucs1(unicode, errors, 256);
6856 Py_DECREF(unicode);
6857 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006858}
6859
Alexander Belopolsky40018472011-02-26 01:02:56 +00006860PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006861_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862{
6863 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006864 PyErr_BadArgument();
6865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006867 if (PyUnicode_READY(unicode) == -1)
6868 return NULL;
6869 /* Fast path: if it is a one-byte string, construct
6870 bytes object directly. */
6871 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6872 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6873 PyUnicode_GET_LENGTH(unicode));
6874 /* Non-Latin-1 characters present. Defer to above function to
6875 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006876 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006877}
6878
6879PyObject*
6880PyUnicode_AsLatin1String(PyObject *unicode)
6881{
6882 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006883}
6884
6885/* --- 7-bit ASCII Codec -------------------------------------------------- */
6886
Alexander Belopolsky40018472011-02-26 01:02:56 +00006887PyObject *
6888PyUnicode_DecodeASCII(const char *s,
6889 Py_ssize_t size,
6890 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006891{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006892 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006893 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006894 int kind;
6895 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006896 Py_ssize_t startinpos;
6897 Py_ssize_t endinpos;
6898 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006899 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006900 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006901 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006902 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006903
Guido van Rossumd57fd912000-03-10 22:53:23 +00006904 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006905 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006906
Guido van Rossumd57fd912000-03-10 22:53:23 +00006907 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006908 if (size == 1 && (unsigned char)s[0] < 128)
6909 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006910
Victor Stinner8f674cc2013-04-17 23:02:17 +02006911 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006912 writer.min_length = size;
6913 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006914 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006915
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006916 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006917 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006918 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006919 writer.pos = outpos;
6920 if (writer.pos == size)
6921 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006922
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006923 s += writer.pos;
6924 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006925 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006926 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006928 PyUnicode_WRITE(kind, data, writer.pos, c);
6929 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006930 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006931 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006932 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006933
6934 /* byte outsize range 0x00..0x7f: call the error handler */
6935
6936 if (error_handler == _Py_ERROR_UNKNOWN)
6937 error_handler = get_error_handler(errors);
6938
6939 switch (error_handler)
6940 {
6941 case _Py_ERROR_REPLACE:
6942 case _Py_ERROR_SURROGATEESCAPE:
6943 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006944 but we may switch to UCS2 at the first write */
6945 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6946 goto onError;
6947 kind = writer.kind;
6948 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006949
6950 if (error_handler == _Py_ERROR_REPLACE)
6951 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6952 else
6953 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6954 writer.pos++;
6955 ++s;
6956 break;
6957
6958 case _Py_ERROR_IGNORE:
6959 ++s;
6960 break;
6961
6962 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006963 startinpos = s-starts;
6964 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006965 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006966 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006967 "ascii", "ordinal not in range(128)",
6968 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006969 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006970 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006971 kind = writer.kind;
6972 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006973 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006974 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006975 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006976 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006977 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006978
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006980 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006981 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006982 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006983 return NULL;
6984}
6985
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006986/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006987PyObject *
6988PyUnicode_EncodeASCII(const Py_UNICODE *p,
6989 Py_ssize_t size,
6990 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006991{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006992 PyObject *result;
6993 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6994 if (unicode == NULL)
6995 return NULL;
6996 result = unicode_encode_ucs1(unicode, errors, 128);
6997 Py_DECREF(unicode);
6998 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999}
7000
Alexander Belopolsky40018472011-02-26 01:02:56 +00007001PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007002_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007003{
7004 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007005 PyErr_BadArgument();
7006 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007007 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007008 if (PyUnicode_READY(unicode) == -1)
7009 return NULL;
7010 /* Fast path: if it is an ASCII-only string, construct bytes object
7011 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007012 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007013 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7014 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007015 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007016}
7017
7018PyObject *
7019PyUnicode_AsASCIIString(PyObject *unicode)
7020{
7021 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007022}
7023
Victor Stinner99b95382011-07-04 14:23:54 +02007024#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007025
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007026/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007027
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007028#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029#define NEED_RETRY
7030#endif
7031
Victor Stinner3a50e702011-10-18 21:21:00 +02007032#ifndef WC_ERR_INVALID_CHARS
7033# define WC_ERR_INVALID_CHARS 0x0080
7034#endif
7035
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007036static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007037code_page_name(UINT code_page, PyObject **obj)
7038{
7039 *obj = NULL;
7040 if (code_page == CP_ACP)
7041 return "mbcs";
7042 if (code_page == CP_UTF7)
7043 return "CP_UTF7";
7044 if (code_page == CP_UTF8)
7045 return "CP_UTF8";
7046
7047 *obj = PyBytes_FromFormat("cp%u", code_page);
7048 if (*obj == NULL)
7049 return NULL;
7050 return PyBytes_AS_STRING(*obj);
7051}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052
Victor Stinner3a50e702011-10-18 21:21:00 +02007053static DWORD
7054decode_code_page_flags(UINT code_page)
7055{
7056 if (code_page == CP_UTF7) {
7057 /* The CP_UTF7 decoder only supports flags=0 */
7058 return 0;
7059 }
7060 else
7061 return MB_ERR_INVALID_CHARS;
7062}
7063
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007064/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 * Decode a byte string from a Windows code page into unicode object in strict
7066 * mode.
7067 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007068 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7069 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007070 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007071static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007072decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007073 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 const char *in,
7075 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007076{
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007078 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007079 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080
7081 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 assert(insize > 0);
7083 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7084 if (outsize <= 0)
7085 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
7087 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007089 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007090 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 if (*v == NULL)
7092 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007094 }
7095 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007096 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007098 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007099 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007100 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007101 }
7102
7103 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7105 if (outsize <= 0)
7106 goto error;
7107 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109error:
7110 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7111 return -2;
7112 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007113 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114}
7115
Victor Stinner3a50e702011-10-18 21:21:00 +02007116/*
7117 * Decode a byte string from a code page into unicode object with an error
7118 * handler.
7119 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007120 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 * UnicodeDecodeError exception and returns -1 on error.
7122 */
7123static int
7124decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007125 PyObject **v,
7126 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007127 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007128{
7129 const char *startin = in;
7130 const char *endin = in + size;
7131 const DWORD flags = decode_code_page_flags(code_page);
7132 /* Ideally, we should get reason from FormatMessage. This is the Windows
7133 2000 English version of the message. */
7134 const char *reason = "No mapping for the Unicode character exists "
7135 "in the target code page.";
7136 /* each step cannot decode more than 1 character, but a character can be
7137 represented as a surrogate pair */
7138 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007139 int insize;
7140 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 PyObject *errorHandler = NULL;
7142 PyObject *exc = NULL;
7143 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007144 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 DWORD err;
7146 int ret = -1;
7147
7148 assert(size > 0);
7149
7150 encoding = code_page_name(code_page, &encoding_obj);
7151 if (encoding == NULL)
7152 return -1;
7153
Victor Stinner7d00cc12014-03-17 23:08:06 +01007154 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7156 UnicodeDecodeError. */
7157 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7158 if (exc != NULL) {
7159 PyCodec_StrictErrors(exc);
7160 Py_CLEAR(exc);
7161 }
7162 goto error;
7163 }
7164
7165 if (*v == NULL) {
7166 /* Create unicode object */
7167 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7168 PyErr_NoMemory();
7169 goto error;
7170 }
Victor Stinnerab595942011-12-17 04:59:06 +01007171 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007172 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 if (*v == NULL)
7174 goto error;
7175 startout = PyUnicode_AS_UNICODE(*v);
7176 }
7177 else {
7178 /* Extend unicode object */
7179 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7180 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7181 PyErr_NoMemory();
7182 goto error;
7183 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007184 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 goto error;
7186 startout = PyUnicode_AS_UNICODE(*v) + n;
7187 }
7188
7189 /* Decode the byte string character per character */
7190 out = startout;
7191 while (in < endin)
7192 {
7193 /* Decode a character */
7194 insize = 1;
7195 do
7196 {
7197 outsize = MultiByteToWideChar(code_page, flags,
7198 in, insize,
7199 buffer, Py_ARRAY_LENGTH(buffer));
7200 if (outsize > 0)
7201 break;
7202 err = GetLastError();
7203 if (err != ERROR_NO_UNICODE_TRANSLATION
7204 && err != ERROR_INSUFFICIENT_BUFFER)
7205 {
7206 PyErr_SetFromWindowsErr(0);
7207 goto error;
7208 }
7209 insize++;
7210 }
7211 /* 4=maximum length of a UTF-8 sequence */
7212 while (insize <= 4 && (in + insize) <= endin);
7213
7214 if (outsize <= 0) {
7215 Py_ssize_t startinpos, endinpos, outpos;
7216
Victor Stinner7d00cc12014-03-17 23:08:06 +01007217 /* last character in partial decode? */
7218 if (in + insize >= endin && !final)
7219 break;
7220
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 startinpos = in - startin;
7222 endinpos = startinpos + 1;
7223 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007224 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 errors, &errorHandler,
7226 encoding, reason,
7227 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007228 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 {
7230 goto error;
7231 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007232 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 }
7234 else {
7235 in += insize;
7236 memcpy(out, buffer, outsize * sizeof(wchar_t));
7237 out += outsize;
7238 }
7239 }
7240
7241 /* write a NUL character at the end */
7242 *out = 0;
7243
7244 /* Extend unicode object */
7245 outsize = out - startout;
7246 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007247 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007249 /* (in - startin) <= size and size is an int */
7250 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007251
7252error:
7253 Py_XDECREF(encoding_obj);
7254 Py_XDECREF(errorHandler);
7255 Py_XDECREF(exc);
7256 return ret;
7257}
7258
Victor Stinner3a50e702011-10-18 21:21:00 +02007259static PyObject *
7260decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007261 const char *s, Py_ssize_t size,
7262 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263{
Victor Stinner76a31a62011-11-04 00:05:13 +01007264 PyObject *v = NULL;
7265 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 if (code_page < 0) {
7268 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7269 return NULL;
7270 }
7271
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007272 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007273 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274
Victor Stinner76a31a62011-11-04 00:05:13 +01007275 do
7276 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 if (size > INT_MAX) {
7279 chunk_size = INT_MAX;
7280 final = 0;
7281 done = 0;
7282 }
7283 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007284#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007285 {
7286 chunk_size = (int)size;
7287 final = (consumed == NULL);
7288 done = 1;
7289 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007290
Victor Stinner76a31a62011-11-04 00:05:13 +01007291 if (chunk_size == 0 && done) {
7292 if (v != NULL)
7293 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007294 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007296
Victor Stinner76a31a62011-11-04 00:05:13 +01007297 converted = decode_code_page_strict(code_page, &v,
7298 s, chunk_size);
7299 if (converted == -2)
7300 converted = decode_code_page_errors(code_page, &v,
7301 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007302 errors, final);
7303 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007304
7305 if (converted < 0) {
7306 Py_XDECREF(v);
7307 return NULL;
7308 }
7309
7310 if (consumed)
7311 *consumed += converted;
7312
7313 s += converted;
7314 size -= converted;
7315 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007316
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007317 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318}
7319
Alexander Belopolsky40018472011-02-26 01:02:56 +00007320PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007321PyUnicode_DecodeCodePageStateful(int code_page,
7322 const char *s,
7323 Py_ssize_t size,
7324 const char *errors,
7325 Py_ssize_t *consumed)
7326{
7327 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7328}
7329
7330PyObject *
7331PyUnicode_DecodeMBCSStateful(const char *s,
7332 Py_ssize_t size,
7333 const char *errors,
7334 Py_ssize_t *consumed)
7335{
7336 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7337}
7338
7339PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007340PyUnicode_DecodeMBCS(const char *s,
7341 Py_ssize_t size,
7342 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007343{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007344 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7345}
7346
Victor Stinner3a50e702011-10-18 21:21:00 +02007347static DWORD
7348encode_code_page_flags(UINT code_page, const char *errors)
7349{
7350 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007351 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007352 }
7353 else if (code_page == CP_UTF7) {
7354 /* CP_UTF7 only supports flags=0 */
7355 return 0;
7356 }
7357 else {
7358 if (errors != NULL && strcmp(errors, "replace") == 0)
7359 return 0;
7360 else
7361 return WC_NO_BEST_FIT_CHARS;
7362 }
7363}
7364
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007366 * Encode a Unicode string to a Windows code page into a byte string in strict
7367 * mode.
7368 *
7369 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007370 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007371 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007372static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007373encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007374 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376{
Victor Stinner554f3f02010-06-16 23:33:54 +00007377 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 BOOL *pusedDefaultChar = &usedDefaultChar;
7379 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007380 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007381 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 const DWORD flags = encode_code_page_flags(code_page, NULL);
7383 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 /* Create a substring so that we can get the UTF-16 representation
7385 of just the slice under consideration. */
7386 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007387
Martin v. Löwis3d325192011-11-04 18:23:06 +01007388 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007389
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007391 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007393 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007394
Victor Stinner2fc507f2011-11-04 20:06:39 +01007395 substring = PyUnicode_Substring(unicode, offset, offset+len);
7396 if (substring == NULL)
7397 return -1;
7398 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7399 if (p == NULL) {
7400 Py_DECREF(substring);
7401 return -1;
7402 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007403 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007404
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007405 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007407 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 NULL, 0,
7409 NULL, pusedDefaultChar);
7410 if (outsize <= 0)
7411 goto error;
7412 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007413 if (pusedDefaultChar && *pusedDefaultChar) {
7414 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007416 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007417
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007419 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007421 if (*outbytes == NULL) {
7422 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007423 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007426 }
7427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007428 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 const Py_ssize_t n = PyBytes_Size(*outbytes);
7430 if (outsize > PY_SSIZE_T_MAX - n) {
7431 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007433 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7436 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007438 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007440 }
7441
7442 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007443 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007444 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 out, outsize,
7446 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 if (outsize <= 0)
7449 goto error;
7450 if (pusedDefaultChar && *pusedDefaultChar)
7451 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007452 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007453
Victor Stinner3a50e702011-10-18 21:21:00 +02007454error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7457 return -2;
7458 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007459 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007460}
7461
Victor Stinner3a50e702011-10-18 21:21:00 +02007462/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007463 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 * error handler.
7465 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007466 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 * -1 on other error.
7468 */
7469static int
7470encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007473{
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 Py_ssize_t pos = unicode_offset;
7476 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007477 /* Ideally, we should get reason from FormatMessage. This is the Windows
7478 2000 English version of the message. */
7479 const char *reason = "invalid character";
7480 /* 4=maximum length of a UTF-8 sequence */
7481 char buffer[4];
7482 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7483 Py_ssize_t outsize;
7484 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 PyObject *errorHandler = NULL;
7486 PyObject *exc = NULL;
7487 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007488 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 PyObject *rep;
7491 int ret = -1;
7492
7493 assert(insize > 0);
7494
7495 encoding = code_page_name(code_page, &encoding_obj);
7496 if (encoding == NULL)
7497 return -1;
7498
7499 if (errors == NULL || strcmp(errors, "strict") == 0) {
7500 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7501 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007502 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007503 if (exc != NULL) {
7504 PyCodec_StrictErrors(exc);
7505 Py_DECREF(exc);
7506 }
7507 Py_XDECREF(encoding_obj);
7508 return -1;
7509 }
7510
7511 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7512 pusedDefaultChar = &usedDefaultChar;
7513 else
7514 pusedDefaultChar = NULL;
7515
7516 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7517 PyErr_NoMemory();
7518 goto error;
7519 }
7520 outsize = insize * Py_ARRAY_LENGTH(buffer);
7521
7522 if (*outbytes == NULL) {
7523 /* Create string object */
7524 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7525 if (*outbytes == NULL)
7526 goto error;
7527 out = PyBytes_AS_STRING(*outbytes);
7528 }
7529 else {
7530 /* Extend string object */
7531 Py_ssize_t n = PyBytes_Size(*outbytes);
7532 if (n > PY_SSIZE_T_MAX - outsize) {
7533 PyErr_NoMemory();
7534 goto error;
7535 }
7536 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7537 goto error;
7538 out = PyBytes_AS_STRING(*outbytes) + n;
7539 }
7540
7541 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007542 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007543 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007544 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7545 wchar_t chars[2];
7546 int charsize;
7547 if (ch < 0x10000) {
7548 chars[0] = (wchar_t)ch;
7549 charsize = 1;
7550 }
7551 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007552 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7553 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007554 charsize = 2;
7555 }
7556
Victor Stinner3a50e702011-10-18 21:21:00 +02007557 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007558 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007559 buffer, Py_ARRAY_LENGTH(buffer),
7560 NULL, pusedDefaultChar);
7561 if (outsize > 0) {
7562 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7563 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007564 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007565 memcpy(out, buffer, outsize);
7566 out += outsize;
7567 continue;
7568 }
7569 }
7570 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7571 PyErr_SetFromWindowsErr(0);
7572 goto error;
7573 }
7574
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 rep = unicode_encode_call_errorhandler(
7576 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007577 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007578 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007579 if (rep == NULL)
7580 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007581 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007582
7583 if (PyBytes_Check(rep)) {
7584 outsize = PyBytes_GET_SIZE(rep);
7585 if (outsize != 1) {
7586 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7587 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7588 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7589 Py_DECREF(rep);
7590 goto error;
7591 }
7592 out = PyBytes_AS_STRING(*outbytes) + offset;
7593 }
7594 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7595 out += outsize;
7596 }
7597 else {
7598 Py_ssize_t i;
7599 enum PyUnicode_Kind kind;
7600 void *data;
7601
Benjamin Petersonbac79492012-01-14 13:34:47 -05007602 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007603 Py_DECREF(rep);
7604 goto error;
7605 }
7606
7607 outsize = PyUnicode_GET_LENGTH(rep);
7608 if (outsize != 1) {
7609 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7610 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7611 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7612 Py_DECREF(rep);
7613 goto error;
7614 }
7615 out = PyBytes_AS_STRING(*outbytes) + offset;
7616 }
7617 kind = PyUnicode_KIND(rep);
7618 data = PyUnicode_DATA(rep);
7619 for (i=0; i < outsize; i++) {
7620 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7621 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007622 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007623 encoding, unicode,
7624 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007625 "unable to encode error handler result to ASCII");
7626 Py_DECREF(rep);
7627 goto error;
7628 }
7629 *out = (unsigned char)ch;
7630 out++;
7631 }
7632 }
7633 Py_DECREF(rep);
7634 }
7635 /* write a NUL byte */
7636 *out = 0;
7637 outsize = out - PyBytes_AS_STRING(*outbytes);
7638 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7639 if (_PyBytes_Resize(outbytes, outsize) < 0)
7640 goto error;
7641 ret = 0;
7642
7643error:
7644 Py_XDECREF(encoding_obj);
7645 Py_XDECREF(errorHandler);
7646 Py_XDECREF(exc);
7647 return ret;
7648}
7649
Victor Stinner3a50e702011-10-18 21:21:00 +02007650static PyObject *
7651encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007652 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007653 const char *errors)
7654{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007655 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007656 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007657 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007658 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007659
Victor Stinner29dacf22015-01-26 16:41:32 +01007660 if (!PyUnicode_Check(unicode)) {
7661 PyErr_BadArgument();
7662 return NULL;
7663 }
7664
Benjamin Petersonbac79492012-01-14 13:34:47 -05007665 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007666 return NULL;
7667 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007668
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 if (code_page < 0) {
7670 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7671 return NULL;
7672 }
7673
Martin v. Löwis3d325192011-11-04 18:23:06 +01007674 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007675 return PyBytes_FromStringAndSize(NULL, 0);
7676
Victor Stinner7581cef2011-11-03 22:32:33 +01007677 offset = 0;
7678 do
7679 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007680#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007681 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007682 chunks. */
7683 if (len > INT_MAX/2) {
7684 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007685 done = 0;
7686 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007687 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007688#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007689 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007690 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 done = 1;
7692 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007693
Victor Stinner76a31a62011-11-04 00:05:13 +01007694 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007695 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 errors);
7697 if (ret == -2)
7698 ret = encode_code_page_errors(code_page, &outbytes,
7699 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007700 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007701 if (ret < 0) {
7702 Py_XDECREF(outbytes);
7703 return NULL;
7704 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007705
Victor Stinner7581cef2011-11-03 22:32:33 +01007706 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007707 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007708 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007709
Victor Stinner3a50e702011-10-18 21:21:00 +02007710 return outbytes;
7711}
7712
7713PyObject *
7714PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7715 Py_ssize_t size,
7716 const char *errors)
7717{
Victor Stinner7581cef2011-11-03 22:32:33 +01007718 PyObject *unicode, *res;
7719 unicode = PyUnicode_FromUnicode(p, size);
7720 if (unicode == NULL)
7721 return NULL;
7722 res = encode_code_page(CP_ACP, unicode, errors);
7723 Py_DECREF(unicode);
7724 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007725}
7726
7727PyObject *
7728PyUnicode_EncodeCodePage(int code_page,
7729 PyObject *unicode,
7730 const char *errors)
7731{
Victor Stinner7581cef2011-11-03 22:32:33 +01007732 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007733}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007734
Alexander Belopolsky40018472011-02-26 01:02:56 +00007735PyObject *
7736PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007737{
Victor Stinner7581cef2011-11-03 22:32:33 +01007738 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007739}
7740
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007741#undef NEED_RETRY
7742
Victor Stinner99b95382011-07-04 14:23:54 +02007743#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007744
Guido van Rossumd57fd912000-03-10 22:53:23 +00007745/* --- Character Mapping Codec -------------------------------------------- */
7746
Victor Stinnerfb161b12013-04-18 01:44:27 +02007747static int
7748charmap_decode_string(const char *s,
7749 Py_ssize_t size,
7750 PyObject *mapping,
7751 const char *errors,
7752 _PyUnicodeWriter *writer)
7753{
7754 const char *starts = s;
7755 const char *e;
7756 Py_ssize_t startinpos, endinpos;
7757 PyObject *errorHandler = NULL, *exc = NULL;
7758 Py_ssize_t maplen;
7759 enum PyUnicode_Kind mapkind;
7760 void *mapdata;
7761 Py_UCS4 x;
7762 unsigned char ch;
7763
7764 if (PyUnicode_READY(mapping) == -1)
7765 return -1;
7766
7767 maplen = PyUnicode_GET_LENGTH(mapping);
7768 mapdata = PyUnicode_DATA(mapping);
7769 mapkind = PyUnicode_KIND(mapping);
7770
7771 e = s + size;
7772
7773 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7774 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7775 * is disabled in encoding aliases, latin1 is preferred because
7776 * its implementation is faster. */
7777 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7778 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7779 Py_UCS4 maxchar = writer->maxchar;
7780
7781 assert (writer->kind == PyUnicode_1BYTE_KIND);
7782 while (s < e) {
7783 ch = *s;
7784 x = mapdata_ucs1[ch];
7785 if (x > maxchar) {
7786 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7787 goto onError;
7788 maxchar = writer->maxchar;
7789 outdata = (Py_UCS1 *)writer->data;
7790 }
7791 outdata[writer->pos] = x;
7792 writer->pos++;
7793 ++s;
7794 }
7795 return 0;
7796 }
7797
7798 while (s < e) {
7799 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7800 enum PyUnicode_Kind outkind = writer->kind;
7801 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7802 if (outkind == PyUnicode_1BYTE_KIND) {
7803 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7804 Py_UCS4 maxchar = writer->maxchar;
7805 while (s < e) {
7806 ch = *s;
7807 x = mapdata_ucs2[ch];
7808 if (x > maxchar)
7809 goto Error;
7810 outdata[writer->pos] = x;
7811 writer->pos++;
7812 ++s;
7813 }
7814 break;
7815 }
7816 else if (outkind == PyUnicode_2BYTE_KIND) {
7817 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7818 while (s < e) {
7819 ch = *s;
7820 x = mapdata_ucs2[ch];
7821 if (x == 0xFFFE)
7822 goto Error;
7823 outdata[writer->pos] = x;
7824 writer->pos++;
7825 ++s;
7826 }
7827 break;
7828 }
7829 }
7830 ch = *s;
7831
7832 if (ch < maplen)
7833 x = PyUnicode_READ(mapkind, mapdata, ch);
7834 else
7835 x = 0xfffe; /* invalid value */
7836Error:
7837 if (x == 0xfffe)
7838 {
7839 /* undefined mapping */
7840 startinpos = s-starts;
7841 endinpos = startinpos+1;
7842 if (unicode_decode_call_errorhandler_writer(
7843 errors, &errorHandler,
7844 "charmap", "character maps to <undefined>",
7845 &starts, &e, &startinpos, &endinpos, &exc, &s,
7846 writer)) {
7847 goto onError;
7848 }
7849 continue;
7850 }
7851
7852 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7853 goto onError;
7854 ++s;
7855 }
7856 Py_XDECREF(errorHandler);
7857 Py_XDECREF(exc);
7858 return 0;
7859
7860onError:
7861 Py_XDECREF(errorHandler);
7862 Py_XDECREF(exc);
7863 return -1;
7864}
7865
7866static int
7867charmap_decode_mapping(const char *s,
7868 Py_ssize_t size,
7869 PyObject *mapping,
7870 const char *errors,
7871 _PyUnicodeWriter *writer)
7872{
7873 const char *starts = s;
7874 const char *e;
7875 Py_ssize_t startinpos, endinpos;
7876 PyObject *errorHandler = NULL, *exc = NULL;
7877 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007878 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007879
7880 e = s + size;
7881
7882 while (s < e) {
7883 ch = *s;
7884
7885 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7886 key = PyLong_FromLong((long)ch);
7887 if (key == NULL)
7888 goto onError;
7889
7890 item = PyObject_GetItem(mapping, key);
7891 Py_DECREF(key);
7892 if (item == NULL) {
7893 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7894 /* No mapping found means: mapping is undefined. */
7895 PyErr_Clear();
7896 goto Undefined;
7897 } else
7898 goto onError;
7899 }
7900
7901 /* Apply mapping */
7902 if (item == Py_None)
7903 goto Undefined;
7904 if (PyLong_Check(item)) {
7905 long value = PyLong_AS_LONG(item);
7906 if (value == 0xFFFE)
7907 goto Undefined;
7908 if (value < 0 || value > MAX_UNICODE) {
7909 PyErr_Format(PyExc_TypeError,
7910 "character mapping must be in range(0x%lx)",
7911 (unsigned long)MAX_UNICODE + 1);
7912 goto onError;
7913 }
7914
7915 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7916 goto onError;
7917 }
7918 else if (PyUnicode_Check(item)) {
7919 if (PyUnicode_READY(item) == -1)
7920 goto onError;
7921 if (PyUnicode_GET_LENGTH(item) == 1) {
7922 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7923 if (value == 0xFFFE)
7924 goto Undefined;
7925 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7926 goto onError;
7927 }
7928 else {
7929 writer->overallocate = 1;
7930 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7931 goto onError;
7932 }
7933 }
7934 else {
7935 /* wrong return value */
7936 PyErr_SetString(PyExc_TypeError,
7937 "character mapping must return integer, None or str");
7938 goto onError;
7939 }
7940 Py_CLEAR(item);
7941 ++s;
7942 continue;
7943
7944Undefined:
7945 /* undefined mapping */
7946 Py_CLEAR(item);
7947 startinpos = s-starts;
7948 endinpos = startinpos+1;
7949 if (unicode_decode_call_errorhandler_writer(
7950 errors, &errorHandler,
7951 "charmap", "character maps to <undefined>",
7952 &starts, &e, &startinpos, &endinpos, &exc, &s,
7953 writer)) {
7954 goto onError;
7955 }
7956 }
7957 Py_XDECREF(errorHandler);
7958 Py_XDECREF(exc);
7959 return 0;
7960
7961onError:
7962 Py_XDECREF(item);
7963 Py_XDECREF(errorHandler);
7964 Py_XDECREF(exc);
7965 return -1;
7966}
7967
Alexander Belopolsky40018472011-02-26 01:02:56 +00007968PyObject *
7969PyUnicode_DecodeCharmap(const char *s,
7970 Py_ssize_t size,
7971 PyObject *mapping,
7972 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007973{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007974 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007975
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976 /* Default to Latin-1 */
7977 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007978 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007979
Guido van Rossumd57fd912000-03-10 22:53:23 +00007980 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007981 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007982 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007983 writer.min_length = size;
7984 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007986
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007987 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007988 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7989 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007990 }
7991 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007992 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7993 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007994 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007995 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007996
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007998 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999 return NULL;
8000}
8001
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002/* Charmap encoding: the lookup table */
8003
Alexander Belopolsky40018472011-02-26 01:02:56 +00008004struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 PyObject_HEAD
8006 unsigned char level1[32];
8007 int count2, count3;
8008 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008009};
8010
8011static PyObject*
8012encoding_map_size(PyObject *obj, PyObject* args)
8013{
8014 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008015 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017}
8018
8019static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008020 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 PyDoc_STR("Return the size (in bytes) of this object") },
8022 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008023};
8024
8025static void
8026encoding_map_dealloc(PyObject* o)
8027{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008028 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029}
8030
8031static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008032 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 "EncodingMap", /*tp_name*/
8034 sizeof(struct encoding_map), /*tp_basicsize*/
8035 0, /*tp_itemsize*/
8036 /* methods */
8037 encoding_map_dealloc, /*tp_dealloc*/
8038 0, /*tp_print*/
8039 0, /*tp_getattr*/
8040 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008041 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 0, /*tp_repr*/
8043 0, /*tp_as_number*/
8044 0, /*tp_as_sequence*/
8045 0, /*tp_as_mapping*/
8046 0, /*tp_hash*/
8047 0, /*tp_call*/
8048 0, /*tp_str*/
8049 0, /*tp_getattro*/
8050 0, /*tp_setattro*/
8051 0, /*tp_as_buffer*/
8052 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8053 0, /*tp_doc*/
8054 0, /*tp_traverse*/
8055 0, /*tp_clear*/
8056 0, /*tp_richcompare*/
8057 0, /*tp_weaklistoffset*/
8058 0, /*tp_iter*/
8059 0, /*tp_iternext*/
8060 encoding_map_methods, /*tp_methods*/
8061 0, /*tp_members*/
8062 0, /*tp_getset*/
8063 0, /*tp_base*/
8064 0, /*tp_dict*/
8065 0, /*tp_descr_get*/
8066 0, /*tp_descr_set*/
8067 0, /*tp_dictoffset*/
8068 0, /*tp_init*/
8069 0, /*tp_alloc*/
8070 0, /*tp_new*/
8071 0, /*tp_free*/
8072 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073};
8074
8075PyObject*
8076PyUnicode_BuildEncodingMap(PyObject* string)
8077{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 PyObject *result;
8079 struct encoding_map *mresult;
8080 int i;
8081 int need_dict = 0;
8082 unsigned char level1[32];
8083 unsigned char level2[512];
8084 unsigned char *mlevel1, *mlevel2, *mlevel3;
8085 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 int kind;
8087 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008088 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008091 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 PyErr_BadArgument();
8093 return NULL;
8094 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008095 kind = PyUnicode_KIND(string);
8096 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008097 length = PyUnicode_GET_LENGTH(string);
8098 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008099 memset(level1, 0xFF, sizeof level1);
8100 memset(level2, 0xFF, sizeof level2);
8101
8102 /* If there isn't a one-to-one mapping of NULL to \0,
8103 or if there are non-BMP characters, we need to use
8104 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008105 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008107 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008109 ch = PyUnicode_READ(kind, data, i);
8110 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 need_dict = 1;
8112 break;
8113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008114 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008115 /* unmapped character */
8116 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008117 l1 = ch >> 11;
8118 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 if (level1[l1] == 0xFF)
8120 level1[l1] = count2++;
8121 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008122 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 }
8124
8125 if (count2 >= 0xFF || count3 >= 0xFF)
8126 need_dict = 1;
8127
8128 if (need_dict) {
8129 PyObject *result = PyDict_New();
8130 PyObject *key, *value;
8131 if (!result)
8132 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008133 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008134 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008135 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 if (!key || !value)
8137 goto failed1;
8138 if (PyDict_SetItem(result, key, value) == -1)
8139 goto failed1;
8140 Py_DECREF(key);
8141 Py_DECREF(value);
8142 }
8143 return result;
8144 failed1:
8145 Py_XDECREF(key);
8146 Py_XDECREF(value);
8147 Py_DECREF(result);
8148 return NULL;
8149 }
8150
8151 /* Create a three-level trie */
8152 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8153 16*count2 + 128*count3 - 1);
8154 if (!result)
8155 return PyErr_NoMemory();
8156 PyObject_Init(result, &EncodingMapType);
8157 mresult = (struct encoding_map*)result;
8158 mresult->count2 = count2;
8159 mresult->count3 = count3;
8160 mlevel1 = mresult->level1;
8161 mlevel2 = mresult->level23;
8162 mlevel3 = mresult->level23 + 16*count2;
8163 memcpy(mlevel1, level1, 32);
8164 memset(mlevel2, 0xFF, 16*count2);
8165 memset(mlevel3, 0, 128*count3);
8166 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008167 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008168 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008169 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8170 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 /* unmapped character */
8172 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008173 o1 = ch>>11;
8174 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008175 i2 = 16*mlevel1[o1] + o2;
8176 if (mlevel2[i2] == 0xFF)
8177 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008178 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 i3 = 128*mlevel2[i2] + o3;
8180 mlevel3[i3] = i;
8181 }
8182 return result;
8183}
8184
8185static int
Victor Stinner22168992011-11-20 17:09:18 +01008186encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187{
8188 struct encoding_map *map = (struct encoding_map*)mapping;
8189 int l1 = c>>11;
8190 int l2 = (c>>7) & 0xF;
8191 int l3 = c & 0x7F;
8192 int i;
8193
Victor Stinner22168992011-11-20 17:09:18 +01008194 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 if (c == 0)
8197 return 0;
8198 /* level 1*/
8199 i = map->level1[l1];
8200 if (i == 0xFF) {
8201 return -1;
8202 }
8203 /* level 2*/
8204 i = map->level23[16*i+l2];
8205 if (i == 0xFF) {
8206 return -1;
8207 }
8208 /* level 3 */
8209 i = map->level23[16*map->count2 + 128*i + l3];
8210 if (i == 0) {
8211 return -1;
8212 }
8213 return i;
8214}
8215
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216/* Lookup the character ch in the mapping. If the character
8217 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008218 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008219static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008220charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008221{
Christian Heimes217cfd12007-12-02 14:31:20 +00008222 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 PyObject *x;
8224
8225 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227 x = PyObject_GetItem(mapping, w);
8228 Py_DECREF(w);
8229 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8231 /* No mapping found means: mapping is undefined. */
8232 PyErr_Clear();
8233 x = Py_None;
8234 Py_INCREF(x);
8235 return x;
8236 } else
8237 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008238 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008239 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008241 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 long value = PyLong_AS_LONG(x);
8243 if (value < 0 || value > 255) {
8244 PyErr_SetString(PyExc_TypeError,
8245 "character mapping must be in range(256)");
8246 Py_DECREF(x);
8247 return NULL;
8248 }
8249 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008250 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008251 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 /* wrong return value */
8255 PyErr_Format(PyExc_TypeError,
8256 "character mapping must return integer, bytes or None, not %.400s",
8257 x->ob_type->tp_name);
8258 Py_DECREF(x);
8259 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008260 }
8261}
8262
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008264charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008265{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008266 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8267 /* exponentially overallocate to minimize reallocations */
8268 if (requiredsize < 2*outsize)
8269 requiredsize = 2*outsize;
8270 if (_PyBytes_Resize(outobj, requiredsize))
8271 return -1;
8272 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008273}
8274
Benjamin Peterson14339b62009-01-31 16:36:08 +00008275typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008277} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008279 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 space is available. Return a new reference to the object that
8281 was put in the output buffer, or Py_None, if the mapping was undefined
8282 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008283 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008284static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008285charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008286 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008288 PyObject *rep;
8289 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008290 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291
Christian Heimes90aa7642007-12-19 02:45:37 +00008292 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008293 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008295 if (res == -1)
8296 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 if (outsize<requiredsize)
8298 if (charmapencode_resize(outobj, outpos, requiredsize))
8299 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008300 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 outstart[(*outpos)++] = (char)res;
8302 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008303 }
8304
8305 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008308 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 Py_DECREF(rep);
8310 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008311 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 if (PyLong_Check(rep)) {
8313 Py_ssize_t requiredsize = *outpos+1;
8314 if (outsize<requiredsize)
8315 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8316 Py_DECREF(rep);
8317 return enc_EXCEPTION;
8318 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008319 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008321 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 else {
8323 const char *repchars = PyBytes_AS_STRING(rep);
8324 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8325 Py_ssize_t requiredsize = *outpos+repsize;
8326 if (outsize<requiredsize)
8327 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8328 Py_DECREF(rep);
8329 return enc_EXCEPTION;
8330 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008331 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 memcpy(outstart + *outpos, repchars, repsize);
8333 *outpos += repsize;
8334 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008336 Py_DECREF(rep);
8337 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338}
8339
8340/* handle an error in PyUnicode_EncodeCharmap
8341 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008342static int
8343charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008344 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008346 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008347 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348{
8349 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008350 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008351 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008352 enum PyUnicode_Kind kind;
8353 void *data;
8354 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008356 Py_ssize_t collstartpos = *inpos;
8357 Py_ssize_t collendpos = *inpos+1;
8358 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 char *encoding = "charmap";
8360 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008361 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008362 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008363 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364
Benjamin Petersonbac79492012-01-14 13:34:47 -05008365 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008366 return -1;
8367 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 /* find all unencodable characters */
8369 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008370 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008371 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008372 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008373 val = encoding_map_lookup(ch, mapping);
8374 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 break;
8376 ++collendpos;
8377 continue;
8378 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008379
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8381 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 if (rep==NULL)
8383 return -1;
8384 else if (rep!=Py_None) {
8385 Py_DECREF(rep);
8386 break;
8387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008388 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008390 }
8391 /* cache callback name lookup
8392 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008393 if (*error_handler == _Py_ERROR_UNKNOWN)
8394 *error_handler = get_error_handler(errors);
8395
8396 switch (*error_handler) {
8397 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008398 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008399 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008400
8401 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008402 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 x = charmapencode_output('?', mapping, res, respos);
8404 if (x==enc_EXCEPTION) {
8405 return -1;
8406 }
8407 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008408 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 return -1;
8410 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008411 }
8412 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008413 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008414 *inpos = collendpos;
8415 break;
Victor Stinner50149202015-09-22 00:26:54 +02008416
8417 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008418 /* generate replacement (temporarily (mis)uses p) */
8419 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 char buffer[2+29+1+1];
8421 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008422 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 for (cp = buffer; *cp; ++cp) {
8424 x = charmapencode_output(*cp, mapping, res, respos);
8425 if (x==enc_EXCEPTION)
8426 return -1;
8427 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008428 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 return -1;
8430 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008431 }
8432 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008433 *inpos = collendpos;
8434 break;
Victor Stinner50149202015-09-22 00:26:54 +02008435
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 default:
Victor Stinner50149202015-09-22 00:26:54 +02008437 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008438 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008440 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008442 if (PyBytes_Check(repunicode)) {
8443 /* Directly copy bytes result to output. */
8444 Py_ssize_t outsize = PyBytes_Size(*res);
8445 Py_ssize_t requiredsize;
8446 repsize = PyBytes_Size(repunicode);
8447 requiredsize = *respos + repsize;
8448 if (requiredsize > outsize)
8449 /* Make room for all additional bytes. */
8450 if (charmapencode_resize(res, respos, requiredsize)) {
8451 Py_DECREF(repunicode);
8452 return -1;
8453 }
8454 memcpy(PyBytes_AsString(*res) + *respos,
8455 PyBytes_AsString(repunicode), repsize);
8456 *respos += repsize;
8457 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008458 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008459 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008460 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008461 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008462 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008463 Py_DECREF(repunicode);
8464 return -1;
8465 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008466 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008467 data = PyUnicode_DATA(repunicode);
8468 kind = PyUnicode_KIND(repunicode);
8469 for (index = 0; index < repsize; index++) {
8470 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8471 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008473 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 return -1;
8475 }
8476 else if (x==enc_FAILED) {
8477 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008478 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 return -1;
8480 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008481 }
8482 *inpos = newpos;
8483 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 }
8485 return 0;
8486}
8487
Alexander Belopolsky40018472011-02-26 01:02:56 +00008488PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008489_PyUnicode_EncodeCharmap(PyObject *unicode,
8490 PyObject *mapping,
8491 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008492{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 /* output object */
8494 PyObject *res = NULL;
8495 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008496 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008497 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008499 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008500 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008502 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008503 void *data;
8504 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008505
Benjamin Petersonbac79492012-01-14 13:34:47 -05008506 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008507 return NULL;
8508 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008509 data = PyUnicode_DATA(unicode);
8510 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008511
Guido van Rossumd57fd912000-03-10 22:53:23 +00008512 /* Default to Latin-1 */
8513 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008515
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 /* allocate enough for a simple encoding without
8517 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008518 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519 if (res == NULL)
8520 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008521 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008523
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008524 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008525 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008527 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 if (x==enc_EXCEPTION) /* error */
8529 goto onError;
8530 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008533 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 &res, &respos)) {
8535 goto onError;
8536 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008537 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 else
8539 /* done with this character => adjust input position */
8540 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008541 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008543 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008544 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008545 if (_PyBytes_Resize(&res, respos) < 0)
8546 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008547
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008549 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550 return res;
8551
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553 Py_XDECREF(res);
8554 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008555 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008556 return NULL;
8557}
8558
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008559/* Deprecated */
8560PyObject *
8561PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8562 Py_ssize_t size,
8563 PyObject *mapping,
8564 const char *errors)
8565{
8566 PyObject *result;
8567 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8568 if (unicode == NULL)
8569 return NULL;
8570 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8571 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008572 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008573}
8574
Alexander Belopolsky40018472011-02-26 01:02:56 +00008575PyObject *
8576PyUnicode_AsCharmapString(PyObject *unicode,
8577 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578{
8579 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008580 PyErr_BadArgument();
8581 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008583 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584}
8585
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008586/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008587static void
8588make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008590 Py_ssize_t startpos, Py_ssize_t endpos,
8591 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008594 *exceptionObject = _PyUnicodeTranslateError_Create(
8595 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596 }
8597 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8599 goto onError;
8600 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8601 goto onError;
8602 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8603 goto onError;
8604 return;
8605 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008606 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607 }
8608}
8609
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610/* error handling callback helper:
8611 build arguments, call the callback and check the arguments,
8612 put the result into newpos and return the replacement string, which
8613 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008614static PyObject *
8615unicode_translate_call_errorhandler(const char *errors,
8616 PyObject **errorHandler,
8617 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008619 Py_ssize_t startpos, Py_ssize_t endpos,
8620 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008622 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008624 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008625 PyObject *restuple;
8626 PyObject *resunicode;
8627
8628 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008630 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008632 }
8633
8634 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638
8639 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008644 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 Py_DECREF(restuple);
8646 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 }
8648 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 &resunicode, &i_newpos)) {
8650 Py_DECREF(restuple);
8651 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008652 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008653 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008655 else
8656 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008658 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008659 Py_DECREF(restuple);
8660 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008661 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008662 Py_INCREF(resunicode);
8663 Py_DECREF(restuple);
8664 return resunicode;
8665}
8666
8667/* Lookup the character ch in the mapping and put the result in result,
8668 which must be decrefed by the caller.
8669 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008670static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672{
Christian Heimes217cfd12007-12-02 14:31:20 +00008673 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674 PyObject *x;
8675
8676 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678 x = PyObject_GetItem(mapping, w);
8679 Py_DECREF(w);
8680 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8682 /* No mapping found means: use 1:1 mapping. */
8683 PyErr_Clear();
8684 *result = NULL;
8685 return 0;
8686 } else
8687 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 }
8689 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 *result = x;
8691 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008692 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008693 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008695 if (value < 0 || value > MAX_UNICODE) {
8696 PyErr_Format(PyExc_ValueError,
8697 "character mapping must be in range(0x%x)",
8698 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008699 Py_DECREF(x);
8700 return -1;
8701 }
8702 *result = x;
8703 return 0;
8704 }
8705 else if (PyUnicode_Check(x)) {
8706 *result = x;
8707 return 0;
8708 }
8709 else {
8710 /* wrong return value */
8711 PyErr_SetString(PyExc_TypeError,
8712 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008713 Py_DECREF(x);
8714 return -1;
8715 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716}
Victor Stinner1194ea02014-04-04 19:37:40 +02008717
8718/* lookup the character, write the result into the writer.
8719 Return 1 if the result was written into the writer, return 0 if the mapping
8720 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008721static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008722charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8723 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008724{
Victor Stinner1194ea02014-04-04 19:37:40 +02008725 PyObject *item;
8726
8727 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008729
8730 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008731 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008732 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008733 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008735 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008737
8738 if (item == Py_None) {
8739 Py_DECREF(item);
8740 return 0;
8741 }
8742
8743 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008744 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8745 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8746 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008747 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8748 Py_DECREF(item);
8749 return -1;
8750 }
8751 Py_DECREF(item);
8752 return 1;
8753 }
8754
8755 if (!PyUnicode_Check(item)) {
8756 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008758 }
8759
8760 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8761 Py_DECREF(item);
8762 return -1;
8763 }
8764
8765 Py_DECREF(item);
8766 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008767}
8768
Victor Stinner89a76ab2014-04-05 11:44:04 +02008769static int
8770unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8771 Py_UCS1 *translate)
8772{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008773 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008774 int ret = 0;
8775
Victor Stinner89a76ab2014-04-05 11:44:04 +02008776 if (charmaptranslate_lookup(ch, mapping, &item)) {
8777 return -1;
8778 }
8779
8780 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008781 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008782 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008783 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008784 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008785 /* not found => default to 1:1 mapping */
8786 translate[ch] = ch;
8787 return 1;
8788 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008789 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008790 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008791 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8792 used it */
8793 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008794 /* invalid character or character outside ASCII:
8795 skip the fast translate */
8796 goto exit;
8797 }
8798 translate[ch] = (Py_UCS1)replace;
8799 }
8800 else if (PyUnicode_Check(item)) {
8801 Py_UCS4 replace;
8802
8803 if (PyUnicode_READY(item) == -1) {
8804 Py_DECREF(item);
8805 return -1;
8806 }
8807 if (PyUnicode_GET_LENGTH(item) != 1)
8808 goto exit;
8809
8810 replace = PyUnicode_READ_CHAR(item, 0);
8811 if (replace > 127)
8812 goto exit;
8813 translate[ch] = (Py_UCS1)replace;
8814 }
8815 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008816 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008817 goto exit;
8818 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819 ret = 1;
8820
Benjamin Peterson1365de72014-04-07 20:15:41 -04008821 exit:
8822 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008823 return ret;
8824}
8825
8826/* Fast path for ascii => ascii translation. Return 1 if the whole string
8827 was translated into writer, return 0 if the input string was partially
8828 translated into writer, raise an exception and return -1 on error. */
8829static int
8830unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008831 _PyUnicodeWriter *writer, int ignore,
8832 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008833{
Victor Stinner872b2912014-04-05 14:27:07 +02008834 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008835 Py_ssize_t len;
8836 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008837 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008838
Victor Stinner89a76ab2014-04-05 11:44:04 +02008839 len = PyUnicode_GET_LENGTH(input);
8840
Victor Stinner872b2912014-04-05 14:27:07 +02008841 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008842
8843 in = PyUnicode_1BYTE_DATA(input);
8844 end = in + len;
8845
8846 assert(PyUnicode_IS_ASCII(writer->buffer));
8847 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8848 out = PyUnicode_1BYTE_DATA(writer->buffer);
8849
Victor Stinner872b2912014-04-05 14:27:07 +02008850 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008852 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008854 int translate = unicode_fast_translate_lookup(mapping, ch,
8855 ascii_table);
8856 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008857 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008858 if (translate == 0)
8859 goto exit;
8860 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008861 }
Victor Stinner872b2912014-04-05 14:27:07 +02008862 if (ch2 == 0xfe) {
8863 if (ignore)
8864 continue;
8865 goto exit;
8866 }
8867 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008868 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008869 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008870 }
Victor Stinner872b2912014-04-05 14:27:07 +02008871 res = 1;
8872
8873exit:
8874 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008875 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008876 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008877}
8878
Victor Stinner3222da22015-10-01 22:07:32 +02008879static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008880_PyUnicode_TranslateCharmap(PyObject *input,
8881 PyObject *mapping,
8882 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008883{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008885 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008886 Py_ssize_t size, i;
8887 int kind;
8888 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008889 _PyUnicodeWriter writer;
8890 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008891 char *reason = "character maps to <undefined>";
8892 PyObject *errorHandler = NULL;
8893 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008894 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008895 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008896
Guido van Rossumd57fd912000-03-10 22:53:23 +00008897 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008898 PyErr_BadArgument();
8899 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008901
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008902 if (PyUnicode_READY(input) == -1)
8903 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008904 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905 kind = PyUnicode_KIND(input);
8906 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008908 if (size == 0)
8909 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008910
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008911 /* allocate enough for a simple 1:1 translation without
8912 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008913 _PyUnicodeWriter_Init(&writer);
8914 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008916
Victor Stinner872b2912014-04-05 14:27:07 +02008917 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8918
Victor Stinner33798672016-03-01 21:59:58 +01008919 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008920 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008921 if (PyUnicode_IS_ASCII(input)) {
8922 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8923 if (res < 0) {
8924 _PyUnicodeWriter_Dealloc(&writer);
8925 return NULL;
8926 }
8927 if (res == 1)
8928 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008929 }
Victor Stinner33798672016-03-01 21:59:58 +01008930 else {
8931 i = 0;
8932 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008933
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008934 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008935 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008936 int translate;
8937 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8938 Py_ssize_t newpos;
8939 /* startpos for collecting untranslatable chars */
8940 Py_ssize_t collstart;
8941 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008942 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008943
Victor Stinner1194ea02014-04-04 19:37:40 +02008944 ch = PyUnicode_READ(kind, data, i);
8945 translate = charmaptranslate_output(ch, mapping, &writer);
8946 if (translate < 0)
8947 goto onError;
8948
8949 if (translate != 0) {
8950 /* it worked => adjust input pointer */
8951 ++i;
8952 continue;
8953 }
8954
8955 /* untranslatable character */
8956 collstart = i;
8957 collend = i+1;
8958
8959 /* find all untranslatable characters */
8960 while (collend < size) {
8961 PyObject *x;
8962 ch = PyUnicode_READ(kind, data, collend);
8963 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008964 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008965 Py_XDECREF(x);
8966 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008967 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008968 ++collend;
8969 }
8970
8971 if (ignore) {
8972 i = collend;
8973 }
8974 else {
8975 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8976 reason, input, &exc,
8977 collstart, collend, &newpos);
8978 if (repunicode == NULL)
8979 goto onError;
8980 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008981 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008983 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008984 Py_DECREF(repunicode);
8985 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008986 }
8987 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008988 Py_XDECREF(exc);
8989 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008990 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008991
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008993 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008994 Py_XDECREF(exc);
8995 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996 return NULL;
8997}
8998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008999/* Deprecated. Use PyUnicode_Translate instead. */
9000PyObject *
9001PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9002 Py_ssize_t size,
9003 PyObject *mapping,
9004 const char *errors)
9005{
Christian Heimes5f520f42012-09-11 14:03:25 +02009006 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9008 if (!unicode)
9009 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009010 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9011 Py_DECREF(unicode);
9012 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009013}
9014
Alexander Belopolsky40018472011-02-26 01:02:56 +00009015PyObject *
9016PyUnicode_Translate(PyObject *str,
9017 PyObject *mapping,
9018 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009019{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009020 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009021 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009022 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009023}
Tim Petersced69f82003-09-16 20:30:58 +00009024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009025static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009026fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027{
9028 /* No need to call PyUnicode_READY(self) because this function is only
9029 called as a callback from fixup() which does it already. */
9030 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9031 const int kind = PyUnicode_KIND(self);
9032 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009033 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009034 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035 Py_ssize_t i;
9036
9037 for (i = 0; i < len; ++i) {
9038 ch = PyUnicode_READ(kind, data, i);
9039 fixed = 0;
9040 if (ch > 127) {
9041 if (Py_UNICODE_ISSPACE(ch))
9042 fixed = ' ';
9043 else {
9044 const int decimal = Py_UNICODE_TODECIMAL(ch);
9045 if (decimal >= 0)
9046 fixed = '0' + decimal;
9047 }
9048 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009049 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009050 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 PyUnicode_WRITE(kind, data, i, fixed);
9052 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009053 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009054 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009055 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009056 }
9057
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009058 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059}
9060
9061PyObject *
9062_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9063{
9064 if (!PyUnicode_Check(unicode)) {
9065 PyErr_BadInternalCall();
9066 return NULL;
9067 }
9068 if (PyUnicode_READY(unicode) == -1)
9069 return NULL;
9070 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9071 /* If the string is already ASCII, just return the same string */
9072 Py_INCREF(unicode);
9073 return unicode;
9074 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009075 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076}
9077
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009078PyObject *
9079PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9080 Py_ssize_t length)
9081{
Victor Stinnerf0124502011-11-21 23:12:56 +01009082 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009083 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009084 Py_UCS4 maxchar;
9085 enum PyUnicode_Kind kind;
9086 void *data;
9087
Victor Stinner99d7ad02012-02-22 13:37:39 +01009088 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009089 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009090 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009091 if (ch > 127) {
9092 int decimal = Py_UNICODE_TODECIMAL(ch);
9093 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009094 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009095 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009096 }
9097 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009098
9099 /* Copy to a new string */
9100 decimal = PyUnicode_New(length, maxchar);
9101 if (decimal == NULL)
9102 return decimal;
9103 kind = PyUnicode_KIND(decimal);
9104 data = PyUnicode_DATA(decimal);
9105 /* Iterate over code points */
9106 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009107 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009108 if (ch > 127) {
9109 int decimal = Py_UNICODE_TODECIMAL(ch);
9110 if (decimal >= 0)
9111 ch = '0' + decimal;
9112 }
9113 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009115 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009116}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009117/* --- Decimal Encoder ---------------------------------------------------- */
9118
Alexander Belopolsky40018472011-02-26 01:02:56 +00009119int
9120PyUnicode_EncodeDecimal(Py_UNICODE *s,
9121 Py_ssize_t length,
9122 char *output,
9123 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009124{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009125 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009126 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009127 enum PyUnicode_Kind kind;
9128 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009129
9130 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009131 PyErr_BadArgument();
9132 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009133 }
9134
Victor Stinner42bf7752011-11-21 22:52:58 +01009135 unicode = PyUnicode_FromUnicode(s, length);
9136 if (unicode == NULL)
9137 return -1;
9138
Benjamin Petersonbac79492012-01-14 13:34:47 -05009139 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009140 Py_DECREF(unicode);
9141 return -1;
9142 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009143 kind = PyUnicode_KIND(unicode);
9144 data = PyUnicode_DATA(unicode);
9145
Victor Stinnerb84d7232011-11-22 01:50:07 +01009146 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009147 PyObject *exc;
9148 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009150 Py_ssize_t startpos;
9151
9152 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009153
Benjamin Peterson29060642009-01-31 22:14:21 +00009154 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009155 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009156 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009158 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009159 decimal = Py_UNICODE_TODECIMAL(ch);
9160 if (decimal >= 0) {
9161 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009162 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009163 continue;
9164 }
9165 if (0 < ch && ch < 256) {
9166 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009167 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 continue;
9169 }
Victor Stinner6345be92011-11-25 20:09:01 +01009170
Victor Stinner42bf7752011-11-21 22:52:58 +01009171 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009172 exc = NULL;
9173 raise_encode_exception(&exc, "decimal", unicode,
9174 startpos, startpos+1,
9175 "invalid decimal Unicode string");
9176 Py_XDECREF(exc);
9177 Py_DECREF(unicode);
9178 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009179 }
9180 /* 0-terminate the output string */
9181 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009182 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009183 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009184}
9185
Guido van Rossumd57fd912000-03-10 22:53:23 +00009186/* --- Helpers ------------------------------------------------------------ */
9187
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009188/* helper macro to fixup start/end slice values */
9189#define ADJUST_INDICES(start, end, len) \
9190 if (end > len) \
9191 end = len; \
9192 else if (end < 0) { \
9193 end += len; \
9194 if (end < 0) \
9195 end = 0; \
9196 } \
9197 if (start < 0) { \
9198 start += len; \
9199 if (start < 0) \
9200 start = 0; \
9201 }
9202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009204any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009206 Py_ssize_t end,
9207 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009209 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 void *buf1, *buf2;
9211 Py_ssize_t len1, len2, result;
9212
9213 kind1 = PyUnicode_KIND(s1);
9214 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009215 if (kind1 < kind2)
9216 return -1;
9217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 len1 = PyUnicode_GET_LENGTH(s1);
9219 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009220 ADJUST_INDICES(start, end, len1);
9221 if (end - start < len2)
9222 return -1;
9223
9224 buf1 = PyUnicode_DATA(s1);
9225 buf2 = PyUnicode_DATA(s2);
9226 if (len2 == 1) {
9227 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9228 result = findchar((const char *)buf1 + kind1*start,
9229 kind1, end - start, ch, direction);
9230 if (result == -1)
9231 return -1;
9232 else
9233 return start + result;
9234 }
9235
9236 if (kind2 != kind1) {
9237 buf2 = _PyUnicode_AsKind(s2, kind1);
9238 if (!buf2)
9239 return -2;
9240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009241
Victor Stinner794d5672011-10-10 03:21:36 +02009242 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009243 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009244 case PyUnicode_1BYTE_KIND:
9245 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9246 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9247 else
9248 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9249 break;
9250 case PyUnicode_2BYTE_KIND:
9251 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9252 break;
9253 case PyUnicode_4BYTE_KIND:
9254 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9255 break;
9256 default:
9257 assert(0); result = -2;
9258 }
9259 }
9260 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009261 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009262 case PyUnicode_1BYTE_KIND:
9263 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9264 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9265 else
9266 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9267 break;
9268 case PyUnicode_2BYTE_KIND:
9269 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9270 break;
9271 case PyUnicode_4BYTE_KIND:
9272 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9273 break;
9274 default:
9275 assert(0); result = -2;
9276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277 }
9278
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009279 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 PyMem_Free(buf2);
9281
9282 return result;
9283}
9284
9285Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009286_PyUnicode_InsertThousandsGrouping(
9287 PyObject *unicode, Py_ssize_t index,
9288 Py_ssize_t n_buffer,
9289 void *digits, Py_ssize_t n_digits,
9290 Py_ssize_t min_width,
9291 const char *grouping, PyObject *thousands_sep,
9292 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293{
Victor Stinner41a863c2012-02-24 00:37:51 +01009294 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009295 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009296 Py_ssize_t thousands_sep_len;
9297 Py_ssize_t len;
9298
9299 if (unicode != NULL) {
9300 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009301 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009302 }
9303 else {
9304 kind = PyUnicode_1BYTE_KIND;
9305 data = NULL;
9306 }
9307 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9308 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9309 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9310 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009311 if (thousands_sep_kind < kind) {
9312 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9313 if (!thousands_sep_data)
9314 return -1;
9315 }
9316 else {
9317 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9318 if (!data)
9319 return -1;
9320 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009321 }
9322
Benjamin Petersonead6b532011-12-20 17:23:42 -06009323 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009325 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009326 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009327 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009328 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009329 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009330 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009331 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009332 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009333 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009334 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009337 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009338 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009339 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009340 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009341 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009343 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009344 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009346 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 break;
9348 default:
9349 assert(0);
9350 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009352 if (unicode != NULL && thousands_sep_kind != kind) {
9353 if (thousands_sep_kind < kind)
9354 PyMem_Free(thousands_sep_data);
9355 else
9356 PyMem_Free(data);
9357 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009358 if (unicode == NULL) {
9359 *maxchar = 127;
9360 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009361 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009362 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009363 }
9364 }
9365 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366}
9367
9368
Alexander Belopolsky40018472011-02-26 01:02:56 +00009369Py_ssize_t
9370PyUnicode_Count(PyObject *str,
9371 PyObject *substr,
9372 Py_ssize_t start,
9373 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009375 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009376 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 void *buf1 = NULL, *buf2 = NULL;
9378 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009379
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009380 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009381 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009382
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009383 kind1 = PyUnicode_KIND(str);
9384 kind2 = PyUnicode_KIND(substr);
9385 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009386 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009387
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009388 len1 = PyUnicode_GET_LENGTH(str);
9389 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009391 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009392 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009393
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009394 buf1 = PyUnicode_DATA(str);
9395 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009396 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009397 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009398 if (!buf2)
9399 goto onError;
9400 }
9401
9402 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009403 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009404 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009405 result = asciilib_count(
9406 ((Py_UCS1*)buf1) + start, end - start,
9407 buf2, len2, PY_SSIZE_T_MAX
9408 );
9409 else
9410 result = ucs1lib_count(
9411 ((Py_UCS1*)buf1) + start, end - start,
9412 buf2, len2, PY_SSIZE_T_MAX
9413 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 break;
9415 case PyUnicode_2BYTE_KIND:
9416 result = ucs2lib_count(
9417 ((Py_UCS2*)buf1) + start, end - start,
9418 buf2, len2, PY_SSIZE_T_MAX
9419 );
9420 break;
9421 case PyUnicode_4BYTE_KIND:
9422 result = ucs4lib_count(
9423 ((Py_UCS4*)buf1) + start, end - start,
9424 buf2, len2, PY_SSIZE_T_MAX
9425 );
9426 break;
9427 default:
9428 assert(0); result = 0;
9429 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009430
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009431 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 PyMem_Free(buf2);
9433
Guido van Rossumd57fd912000-03-10 22:53:23 +00009434 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009435 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009436 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 PyMem_Free(buf2);
9438 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009439}
9440
Alexander Belopolsky40018472011-02-26 01:02:56 +00009441Py_ssize_t
9442PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009443 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009444 Py_ssize_t start,
9445 Py_ssize_t end,
9446 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009448 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009449 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009450
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009451 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452}
9453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009454Py_ssize_t
9455PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9456 Py_ssize_t start, Py_ssize_t end,
9457 int direction)
9458{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009460 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 if (PyUnicode_READY(str) == -1)
9462 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009463 if (start < 0 || end < 0) {
9464 PyErr_SetString(PyExc_IndexError, "string index out of range");
9465 return -2;
9466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467 if (end > PyUnicode_GET_LENGTH(str))
9468 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009469 if (start >= end)
9470 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009472 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9473 kind, end-start, ch, direction);
9474 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009476 else
9477 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478}
9479
Alexander Belopolsky40018472011-02-26 01:02:56 +00009480static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009481tailmatch(PyObject *self,
9482 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009483 Py_ssize_t start,
9484 Py_ssize_t end,
9485 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 int kind_self;
9488 int kind_sub;
9489 void *data_self;
9490 void *data_sub;
9491 Py_ssize_t offset;
9492 Py_ssize_t i;
9493 Py_ssize_t end_sub;
9494
9495 if (PyUnicode_READY(self) == -1 ||
9496 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009497 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9500 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009502 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009504 if (PyUnicode_GET_LENGTH(substring) == 0)
9505 return 1;
9506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507 kind_self = PyUnicode_KIND(self);
9508 data_self = PyUnicode_DATA(self);
9509 kind_sub = PyUnicode_KIND(substring);
9510 data_sub = PyUnicode_DATA(substring);
9511 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9512
9513 if (direction > 0)
9514 offset = end;
9515 else
9516 offset = start;
9517
9518 if (PyUnicode_READ(kind_self, data_self, offset) ==
9519 PyUnicode_READ(kind_sub, data_sub, 0) &&
9520 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9521 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9522 /* If both are of the same kind, memcmp is sufficient */
9523 if (kind_self == kind_sub) {
9524 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009525 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 data_sub,
9527 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009528 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009530 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 else {
9532 /* We do not need to compare 0 and len(substring)-1 because
9533 the if statement above ensured already that they are equal
9534 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 for (i = 1; i < end_sub; ++i) {
9536 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9537 PyUnicode_READ(kind_sub, data_sub, i))
9538 return 0;
9539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009540 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542 }
9543
9544 return 0;
9545}
9546
Alexander Belopolsky40018472011-02-26 01:02:56 +00009547Py_ssize_t
9548PyUnicode_Tailmatch(PyObject *str,
9549 PyObject *substr,
9550 Py_ssize_t start,
9551 Py_ssize_t end,
9552 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009554 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009555 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009556
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009557 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558}
9559
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560/* Apply fixfct filter to the Unicode object self and return a
9561 reference to the modified object */
9562
Alexander Belopolsky40018472011-02-26 01:02:56 +00009563static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009564fixup(PyObject *self,
9565 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009567 PyObject *u;
9568 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009569 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009571 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009573 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009574 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009576 /* fix functions return the new maximum character in a string,
9577 if the kind of the resulting unicode object does not change,
9578 everything is fine. Otherwise we need to change the string kind
9579 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009580 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009581
9582 if (maxchar_new == 0) {
9583 /* no changes */;
9584 if (PyUnicode_CheckExact(self)) {
9585 Py_DECREF(u);
9586 Py_INCREF(self);
9587 return self;
9588 }
9589 else
9590 return u;
9591 }
9592
Victor Stinnere6abb482012-05-02 01:15:40 +02009593 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594
Victor Stinnereaab6042011-12-11 22:22:39 +01009595 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009596 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009597
9598 /* In case the maximum character changed, we need to
9599 convert the string to the new category. */
9600 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9601 if (v == NULL) {
9602 Py_DECREF(u);
9603 return NULL;
9604 }
9605 if (maxchar_new > maxchar_old) {
9606 /* If the maxchar increased so that the kind changed, not all
9607 characters are representable anymore and we need to fix the
9608 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009609 _PyUnicode_FastCopyCharacters(v, 0,
9610 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009611 maxchar_old = fixfct(v);
9612 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 }
9614 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009615 _PyUnicode_FastCopyCharacters(v, 0,
9616 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009618 Py_DECREF(u);
9619 assert(_PyUnicode_CheckConsistency(v, 1));
9620 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621}
9622
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009623static PyObject *
9624ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009626 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9627 char *resdata, *data = PyUnicode_DATA(self);
9628 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009629
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630 res = PyUnicode_New(len, 127);
9631 if (res == NULL)
9632 return NULL;
9633 resdata = PyUnicode_DATA(res);
9634 if (lower)
9635 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009636 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 _Py_bytes_upper(resdata, data, len);
9638 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639}
9640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009642handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644 Py_ssize_t j;
9645 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009646 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009648
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9650
9651 where ! is a negation and \p{xxx} is a character with property xxx.
9652 */
9653 for (j = i - 1; j >= 0; j--) {
9654 c = PyUnicode_READ(kind, data, j);
9655 if (!_PyUnicode_IsCaseIgnorable(c))
9656 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9659 if (final_sigma) {
9660 for (j = i + 1; j < length; j++) {
9661 c = PyUnicode_READ(kind, data, j);
9662 if (!_PyUnicode_IsCaseIgnorable(c))
9663 break;
9664 }
9665 final_sigma = j == length || !_PyUnicode_IsCased(c);
9666 }
9667 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668}
9669
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670static int
9671lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9672 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674 /* Obscure special case. */
9675 if (c == 0x3A3) {
9676 mapped[0] = handle_capital_sigma(kind, data, length, i);
9677 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009679 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680}
9681
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009682static Py_ssize_t
9683do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009685 Py_ssize_t i, k = 0;
9686 int n_res, j;
9687 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009688
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009689 c = PyUnicode_READ(kind, data, 0);
9690 n_res = _PyUnicode_ToUpperFull(c, mapped);
9691 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009692 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695 for (i = 1; i < length; i++) {
9696 c = PyUnicode_READ(kind, data, i);
9697 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9698 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009699 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009700 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009701 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009702 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009703 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009704}
9705
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706static Py_ssize_t
9707do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9708 Py_ssize_t i, k = 0;
9709
9710 for (i = 0; i < length; i++) {
9711 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9712 int n_res, j;
9713 if (Py_UNICODE_ISUPPER(c)) {
9714 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9715 }
9716 else if (Py_UNICODE_ISLOWER(c)) {
9717 n_res = _PyUnicode_ToUpperFull(c, mapped);
9718 }
9719 else {
9720 n_res = 1;
9721 mapped[0] = c;
9722 }
9723 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009724 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009725 res[k++] = mapped[j];
9726 }
9727 }
9728 return k;
9729}
9730
9731static Py_ssize_t
9732do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9733 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009734{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009735 Py_ssize_t i, k = 0;
9736
9737 for (i = 0; i < length; i++) {
9738 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9739 int n_res, j;
9740 if (lower)
9741 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9742 else
9743 n_res = _PyUnicode_ToUpperFull(c, mapped);
9744 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009745 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009746 res[k++] = mapped[j];
9747 }
9748 }
9749 return k;
9750}
9751
9752static Py_ssize_t
9753do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9754{
9755 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9756}
9757
9758static Py_ssize_t
9759do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9760{
9761 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9762}
9763
Benjamin Petersone51757f2012-01-12 21:10:29 -05009764static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009765do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9766{
9767 Py_ssize_t i, k = 0;
9768
9769 for (i = 0; i < length; i++) {
9770 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9771 Py_UCS4 mapped[3];
9772 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9773 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009774 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009775 res[k++] = mapped[j];
9776 }
9777 }
9778 return k;
9779}
9780
9781static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009782do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9783{
9784 Py_ssize_t i, k = 0;
9785 int previous_is_cased;
9786
9787 previous_is_cased = 0;
9788 for (i = 0; i < length; i++) {
9789 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9790 Py_UCS4 mapped[3];
9791 int n_res, j;
9792
9793 if (previous_is_cased)
9794 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9795 else
9796 n_res = _PyUnicode_ToTitleFull(c, mapped);
9797
9798 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009799 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009800 res[k++] = mapped[j];
9801 }
9802
9803 previous_is_cased = _PyUnicode_IsCased(c);
9804 }
9805 return k;
9806}
9807
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009808static PyObject *
9809case_operation(PyObject *self,
9810 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9811{
9812 PyObject *res = NULL;
9813 Py_ssize_t length, newlength = 0;
9814 int kind, outkind;
9815 void *data, *outdata;
9816 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9817
Benjamin Petersoneea48462012-01-16 14:28:50 -05009818 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009819
9820 kind = PyUnicode_KIND(self);
9821 data = PyUnicode_DATA(self);
9822 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009823 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009824 PyErr_SetString(PyExc_OverflowError, "string is too long");
9825 return NULL;
9826 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009827 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009828 if (tmp == NULL)
9829 return PyErr_NoMemory();
9830 newlength = perform(kind, data, length, tmp, &maxchar);
9831 res = PyUnicode_New(newlength, maxchar);
9832 if (res == NULL)
9833 goto leave;
9834 tmpend = tmp + newlength;
9835 outdata = PyUnicode_DATA(res);
9836 outkind = PyUnicode_KIND(res);
9837 switch (outkind) {
9838 case PyUnicode_1BYTE_KIND:
9839 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9840 break;
9841 case PyUnicode_2BYTE_KIND:
9842 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9843 break;
9844 case PyUnicode_4BYTE_KIND:
9845 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9846 break;
9847 default:
9848 assert(0);
9849 break;
9850 }
9851 leave:
9852 PyMem_FREE(tmp);
9853 return res;
9854}
9855
Tim Peters8ce9f162004-08-27 01:49:32 +00009856PyObject *
9857PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009858{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009859 PyObject *res;
9860 PyObject *fseq;
9861 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009862 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009863
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009864 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009865 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009866 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009867 }
9868
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009869 /* NOTE: the following code can't call back into Python code,
9870 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009871 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009872
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009873 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009874 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009875 res = _PyUnicode_JoinArray(separator, items, seqlen);
9876 Py_DECREF(fseq);
9877 return res;
9878}
9879
9880PyObject *
9881_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9882{
9883 PyObject *res = NULL; /* the result */
9884 PyObject *sep = NULL;
9885 Py_ssize_t seplen;
9886 PyObject *item;
9887 Py_ssize_t sz, i, res_offset;
9888 Py_UCS4 maxchar;
9889 Py_UCS4 item_maxchar;
9890 int use_memcpy;
9891 unsigned char *res_data = NULL, *sep_data = NULL;
9892 PyObject *last_obj;
9893 unsigned int kind = 0;
9894
Tim Peters05eba1f2004-08-27 21:32:02 +00009895 /* If empty sequence, return u"". */
9896 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009897 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009898 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009899
Tim Peters05eba1f2004-08-27 21:32:02 +00009900 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009901 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009902 if (seqlen == 1) {
9903 if (PyUnicode_CheckExact(items[0])) {
9904 res = items[0];
9905 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009906 return res;
9907 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009908 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009909 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009910 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009911 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009912 /* Set up sep and seplen */
9913 if (separator == NULL) {
9914 /* fall back to a blank space separator */
9915 sep = PyUnicode_FromOrdinal(' ');
9916 if (!sep)
9917 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009918 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009919 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009920 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009921 else {
9922 if (!PyUnicode_Check(separator)) {
9923 PyErr_Format(PyExc_TypeError,
9924 "separator: expected str instance,"
9925 " %.80s found",
9926 Py_TYPE(separator)->tp_name);
9927 goto onError;
9928 }
9929 if (PyUnicode_READY(separator))
9930 goto onError;
9931 sep = separator;
9932 seplen = PyUnicode_GET_LENGTH(separator);
9933 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9934 /* inc refcount to keep this code path symmetric with the
9935 above case of a blank separator */
9936 Py_INCREF(sep);
9937 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009938 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009939 }
9940
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009941 /* There are at least two things to join, or else we have a subclass
9942 * of str in the sequence.
9943 * Do a pre-pass to figure out the total amount of space we'll
9944 * need (sz), and see whether all argument are strings.
9945 */
9946 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009947#ifdef Py_DEBUG
9948 use_memcpy = 0;
9949#else
9950 use_memcpy = 1;
9951#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009952 for (i = 0; i < seqlen; i++) {
9953 const Py_ssize_t old_sz = sz;
9954 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009955 if (!PyUnicode_Check(item)) {
9956 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009957 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009958 " %.80s found",
9959 i, Py_TYPE(item)->tp_name);
9960 goto onError;
9961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 if (PyUnicode_READY(item) == -1)
9963 goto onError;
9964 sz += PyUnicode_GET_LENGTH(item);
9965 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009966 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009967 if (i != 0)
9968 sz += seplen;
9969 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9970 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009971 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009972 goto onError;
9973 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009974 if (use_memcpy && last_obj != NULL) {
9975 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9976 use_memcpy = 0;
9977 }
9978 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009979 }
Tim Petersced69f82003-09-16 20:30:58 +00009980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009982 if (res == NULL)
9983 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009984
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009985 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009986#ifdef Py_DEBUG
9987 use_memcpy = 0;
9988#else
9989 if (use_memcpy) {
9990 res_data = PyUnicode_1BYTE_DATA(res);
9991 kind = PyUnicode_KIND(res);
9992 if (seplen != 0)
9993 sep_data = PyUnicode_1BYTE_DATA(sep);
9994 }
9995#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009996 if (use_memcpy) {
9997 for (i = 0; i < seqlen; ++i) {
9998 Py_ssize_t itemlen;
9999 item = items[i];
10000
10001 /* Copy item, and maybe the separator. */
10002 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010003 Py_MEMCPY(res_data,
10004 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010005 kind * seplen);
10006 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010007 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010008
10009 itemlen = PyUnicode_GET_LENGTH(item);
10010 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010011 Py_MEMCPY(res_data,
10012 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010013 kind * itemlen);
10014 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010015 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010016 }
10017 assert(res_data == PyUnicode_1BYTE_DATA(res)
10018 + kind * PyUnicode_GET_LENGTH(res));
10019 }
10020 else {
10021 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10022 Py_ssize_t itemlen;
10023 item = items[i];
10024
10025 /* Copy item, and maybe the separator. */
10026 if (i && seplen != 0) {
10027 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10028 res_offset += seplen;
10029 }
10030
10031 itemlen = PyUnicode_GET_LENGTH(item);
10032 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010033 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010034 res_offset += itemlen;
10035 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010036 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010037 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010038 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010041 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043
Benjamin Peterson29060642009-01-31 22:14:21 +000010044 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010046 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047 return NULL;
10048}
10049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050#define FILL(kind, data, value, start, length) \
10051 do { \
10052 Py_ssize_t i_ = 0; \
10053 assert(kind != PyUnicode_WCHAR_KIND); \
10054 switch ((kind)) { \
10055 case PyUnicode_1BYTE_KIND: { \
10056 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010057 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 break; \
10059 } \
10060 case PyUnicode_2BYTE_KIND: { \
10061 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10062 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10063 break; \
10064 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010065 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10067 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10068 break; \
10069 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010070 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 } \
10072 } while (0)
10073
Victor Stinnerd3f08822012-05-29 12:57:52 +020010074void
10075_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10076 Py_UCS4 fill_char)
10077{
10078 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10079 const void *data = PyUnicode_DATA(unicode);
10080 assert(PyUnicode_IS_READY(unicode));
10081 assert(unicode_modifiable(unicode));
10082 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10083 assert(start >= 0);
10084 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10085 FILL(kind, data, fill_char, start, length);
10086}
10087
Victor Stinner3fe55312012-01-04 00:33:50 +010010088Py_ssize_t
10089PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10090 Py_UCS4 fill_char)
10091{
10092 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010093
10094 if (!PyUnicode_Check(unicode)) {
10095 PyErr_BadInternalCall();
10096 return -1;
10097 }
10098 if (PyUnicode_READY(unicode) == -1)
10099 return -1;
10100 if (unicode_check_modifiable(unicode))
10101 return -1;
10102
Victor Stinnerd3f08822012-05-29 12:57:52 +020010103 if (start < 0) {
10104 PyErr_SetString(PyExc_IndexError, "string index out of range");
10105 return -1;
10106 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010107 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10108 PyErr_SetString(PyExc_ValueError,
10109 "fill character is bigger than "
10110 "the string maximum character");
10111 return -1;
10112 }
10113
10114 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10115 length = Py_MIN(maxlen, length);
10116 if (length <= 0)
10117 return 0;
10118
Victor Stinnerd3f08822012-05-29 12:57:52 +020010119 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010120 return length;
10121}
10122
Victor Stinner9310abb2011-10-05 00:59:23 +020010123static PyObject *
10124pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125 Py_ssize_t left,
10126 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 PyObject *u;
10130 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010131 int kind;
10132 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133
10134 if (left < 0)
10135 left = 0;
10136 if (right < 0)
10137 right = 0;
10138
Victor Stinnerc4b49542011-12-11 22:44:26 +010010139 if (left == 0 && right == 0)
10140 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10143 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010144 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10145 return NULL;
10146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010148 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010150 if (!u)
10151 return NULL;
10152
10153 kind = PyUnicode_KIND(u);
10154 data = PyUnicode_DATA(u);
10155 if (left)
10156 FILL(kind, data, fill, 0, left);
10157 if (right)
10158 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010159 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010160 assert(_PyUnicode_CheckConsistency(u, 1));
10161 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162}
10163
Alexander Belopolsky40018472011-02-26 01:02:56 +000010164PyObject *
10165PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010166{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010167 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010169 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010170 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010171
Benjamin Petersonead6b532011-12-20 17:23:42 -060010172 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010174 if (PyUnicode_IS_ASCII(string))
10175 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010176 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010177 PyUnicode_GET_LENGTH(string), keepends);
10178 else
10179 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010180 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010181 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 break;
10183 case PyUnicode_2BYTE_KIND:
10184 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010185 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 PyUnicode_GET_LENGTH(string), keepends);
10187 break;
10188 case PyUnicode_4BYTE_KIND:
10189 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010190 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 PyUnicode_GET_LENGTH(string), keepends);
10192 break;
10193 default:
10194 assert(0);
10195 list = 0;
10196 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010197 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010198}
10199
Alexander Belopolsky40018472011-02-26 01:02:56 +000010200static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010201split(PyObject *self,
10202 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010203 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010204{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010205 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 void *buf1, *buf2;
10207 Py_ssize_t len1, len2;
10208 PyObject* out;
10209
Guido van Rossumd57fd912000-03-10 22:53:23 +000010210 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010211 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 if (PyUnicode_READY(self) == -1)
10214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010217 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 if (PyUnicode_IS_ASCII(self))
10220 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010221 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 PyUnicode_GET_LENGTH(self), maxcount
10223 );
10224 else
10225 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010226 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010227 PyUnicode_GET_LENGTH(self), maxcount
10228 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 case PyUnicode_2BYTE_KIND:
10230 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 PyUnicode_GET_LENGTH(self), maxcount
10233 );
10234 case PyUnicode_4BYTE_KIND:
10235 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010236 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 PyUnicode_GET_LENGTH(self), maxcount
10238 );
10239 default:
10240 assert(0);
10241 return NULL;
10242 }
10243
10244 if (PyUnicode_READY(substring) == -1)
10245 return NULL;
10246
10247 kind1 = PyUnicode_KIND(self);
10248 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 len1 = PyUnicode_GET_LENGTH(self);
10250 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010251 if (kind1 < kind2 || len1 < len2) {
10252 out = PyList_New(1);
10253 if (out == NULL)
10254 return NULL;
10255 Py_INCREF(self);
10256 PyList_SET_ITEM(out, 0, self);
10257 return out;
10258 }
10259 buf1 = PyUnicode_DATA(self);
10260 buf2 = PyUnicode_DATA(substring);
10261 if (kind2 != kind1) {
10262 buf2 = _PyUnicode_AsKind(substring, kind1);
10263 if (!buf2)
10264 return NULL;
10265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010267 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010269 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10270 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010271 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010272 else
10273 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010274 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 break;
10276 case PyUnicode_2BYTE_KIND:
10277 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010278 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 break;
10280 case PyUnicode_4BYTE_KIND:
10281 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010282 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 break;
10284 default:
10285 out = NULL;
10286 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010287 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 PyMem_Free(buf2);
10289 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290}
10291
Alexander Belopolsky40018472011-02-26 01:02:56 +000010292static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010293rsplit(PyObject *self,
10294 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010295 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010296{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010297 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 void *buf1, *buf2;
10299 Py_ssize_t len1, len2;
10300 PyObject* out;
10301
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010302 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010303 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 if (PyUnicode_READY(self) == -1)
10306 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010309 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010311 if (PyUnicode_IS_ASCII(self))
10312 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010313 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010314 PyUnicode_GET_LENGTH(self), maxcount
10315 );
10316 else
10317 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010318 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010319 PyUnicode_GET_LENGTH(self), maxcount
10320 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 case PyUnicode_2BYTE_KIND:
10322 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010323 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 PyUnicode_GET_LENGTH(self), maxcount
10325 );
10326 case PyUnicode_4BYTE_KIND:
10327 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010328 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 PyUnicode_GET_LENGTH(self), maxcount
10330 );
10331 default:
10332 assert(0);
10333 return NULL;
10334 }
10335
10336 if (PyUnicode_READY(substring) == -1)
10337 return NULL;
10338
10339 kind1 = PyUnicode_KIND(self);
10340 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 len1 = PyUnicode_GET_LENGTH(self);
10342 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010343 if (kind1 < kind2 || len1 < len2) {
10344 out = PyList_New(1);
10345 if (out == NULL)
10346 return NULL;
10347 Py_INCREF(self);
10348 PyList_SET_ITEM(out, 0, self);
10349 return out;
10350 }
10351 buf1 = PyUnicode_DATA(self);
10352 buf2 = PyUnicode_DATA(substring);
10353 if (kind2 != kind1) {
10354 buf2 = _PyUnicode_AsKind(substring, kind1);
10355 if (!buf2)
10356 return NULL;
10357 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010359 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010361 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10362 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010363 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010364 else
10365 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010366 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 break;
10368 case PyUnicode_2BYTE_KIND:
10369 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010370 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 break;
10372 case PyUnicode_4BYTE_KIND:
10373 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010374 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 break;
10376 default:
10377 out = NULL;
10378 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010379 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 PyMem_Free(buf2);
10381 return out;
10382}
10383
10384static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010385anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10386 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010388 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010390 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10391 return asciilib_find(buf1, len1, buf2, len2, offset);
10392 else
10393 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 case PyUnicode_2BYTE_KIND:
10395 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10396 case PyUnicode_4BYTE_KIND:
10397 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10398 }
10399 assert(0);
10400 return -1;
10401}
10402
10403static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010404anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10405 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010407 switch (kind) {
10408 case PyUnicode_1BYTE_KIND:
10409 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10410 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10411 else
10412 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10413 case PyUnicode_2BYTE_KIND:
10414 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10415 case PyUnicode_4BYTE_KIND:
10416 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10417 }
10418 assert(0);
10419 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010420}
10421
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010422static void
10423replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10424 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10425{
10426 int kind = PyUnicode_KIND(u);
10427 void *data = PyUnicode_DATA(u);
10428 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10429 if (kind == PyUnicode_1BYTE_KIND) {
10430 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10431 (Py_UCS1 *)data + len,
10432 u1, u2, maxcount);
10433 }
10434 else if (kind == PyUnicode_2BYTE_KIND) {
10435 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10436 (Py_UCS2 *)data + len,
10437 u1, u2, maxcount);
10438 }
10439 else {
10440 assert(kind == PyUnicode_4BYTE_KIND);
10441 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10442 (Py_UCS4 *)data + len,
10443 u1, u2, maxcount);
10444 }
10445}
10446
Alexander Belopolsky40018472011-02-26 01:02:56 +000010447static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448replace(PyObject *self, PyObject *str1,
10449 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010450{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 PyObject *u;
10452 char *sbuf = PyUnicode_DATA(self);
10453 char *buf1 = PyUnicode_DATA(str1);
10454 char *buf2 = PyUnicode_DATA(str2);
10455 int srelease = 0, release1 = 0, release2 = 0;
10456 int skind = PyUnicode_KIND(self);
10457 int kind1 = PyUnicode_KIND(str1);
10458 int kind2 = PyUnicode_KIND(str2);
10459 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10460 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10461 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010462 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010463 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010464
10465 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010466 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010468 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469
Victor Stinner59de0ee2011-10-07 10:01:28 +020010470 if (str1 == str2)
10471 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472
Victor Stinner49a0a212011-10-12 23:46:10 +020010473 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010474 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10475 if (maxchar < maxchar_str1)
10476 /* substring too wide to be present */
10477 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010478 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10479 /* Replacing str1 with str2 may cause a maxchar reduction in the
10480 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010481 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010482 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010485 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010487 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010491 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010492
Victor Stinner69ed0f42013-04-09 21:48:24 +020010493 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010494 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010495 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010497 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010499 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010501
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010502 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10503 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 }
10505 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 int rkind = skind;
10507 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010508 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 if (kind1 < rkind) {
10511 /* widen substring */
10512 buf1 = _PyUnicode_AsKind(str1, rkind);
10513 if (!buf1) goto error;
10514 release1 = 1;
10515 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010516 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010517 if (i < 0)
10518 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 if (rkind > kind2) {
10520 /* widen replacement */
10521 buf2 = _PyUnicode_AsKind(str2, rkind);
10522 if (!buf2) goto error;
10523 release2 = 1;
10524 }
10525 else if (rkind < kind2) {
10526 /* widen self and buf1 */
10527 rkind = kind2;
10528 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010529 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 sbuf = _PyUnicode_AsKind(self, rkind);
10531 if (!sbuf) goto error;
10532 srelease = 1;
10533 buf1 = _PyUnicode_AsKind(str1, rkind);
10534 if (!buf1) goto error;
10535 release1 = 1;
10536 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010537 u = PyUnicode_New(slen, maxchar);
10538 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010540 assert(PyUnicode_KIND(u) == rkind);
10541 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010542
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010543 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010544 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010545 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010547 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010548 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010549
10550 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010551 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010552 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010553 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010554 if (i == -1)
10555 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010556 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010560 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010561 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010562 }
10563 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010565 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 int rkind = skind;
10567 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 buf1 = _PyUnicode_AsKind(str1, rkind);
10572 if (!buf1) goto error;
10573 release1 = 1;
10574 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010575 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576 if (n == 0)
10577 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010579 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 buf2 = _PyUnicode_AsKind(str2, rkind);
10581 if (!buf2) goto error;
10582 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010585 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 rkind = kind2;
10587 sbuf = _PyUnicode_AsKind(self, rkind);
10588 if (!sbuf) goto error;
10589 srelease = 1;
10590 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010591 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 buf1 = _PyUnicode_AsKind(str1, rkind);
10593 if (!buf1) goto error;
10594 release1 = 1;
10595 }
10596 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10597 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010598 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 PyErr_SetString(PyExc_OverflowError,
10600 "replace string is too long");
10601 goto error;
10602 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010603 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010604 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010605 _Py_INCREF_UNICODE_EMPTY();
10606 if (!unicode_empty)
10607 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010608 u = unicode_empty;
10609 goto done;
10610 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010611 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 PyErr_SetString(PyExc_OverflowError,
10613 "replace string is too long");
10614 goto error;
10615 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010616 u = PyUnicode_New(new_size, maxchar);
10617 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010619 assert(PyUnicode_KIND(u) == rkind);
10620 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 ires = i = 0;
10622 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010623 while (n-- > 0) {
10624 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010625 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010626 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010627 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010628 if (j == -1)
10629 break;
10630 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010631 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010632 memcpy(res + rkind * ires,
10633 sbuf + rkind * i,
10634 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010636 }
10637 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010639 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010641 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010643 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010648 memcpy(res + rkind * ires,
10649 sbuf + rkind * i,
10650 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010651 }
10652 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010653 /* interleave */
10654 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010655 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010657 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010659 if (--n <= 0)
10660 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010661 memcpy(res + rkind * ires,
10662 sbuf + rkind * i,
10663 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 ires++;
10665 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010666 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010667 memcpy(res + rkind * ires,
10668 sbuf + rkind * i,
10669 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010671 }
10672
10673 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010674 unicode_adjust_maxchar(&u);
10675 if (u == NULL)
10676 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010678
10679 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 if (srelease)
10681 PyMem_FREE(sbuf);
10682 if (release1)
10683 PyMem_FREE(buf1);
10684 if (release2)
10685 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010686 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010688
Benjamin Peterson29060642009-01-31 22:14:21 +000010689 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010690 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 if (srelease)
10692 PyMem_FREE(sbuf);
10693 if (release1)
10694 PyMem_FREE(buf1);
10695 if (release2)
10696 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010697 return unicode_result_unchanged(self);
10698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699 error:
10700 if (srelease && sbuf)
10701 PyMem_FREE(sbuf);
10702 if (release1 && buf1)
10703 PyMem_FREE(buf1);
10704 if (release2 && buf2)
10705 PyMem_FREE(buf2);
10706 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707}
10708
10709/* --- Unicode Object Methods --------------------------------------------- */
10710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010711PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010712 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010713\n\
10714Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010715characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716
10717static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010718unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010719{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010720 if (PyUnicode_READY(self) == -1)
10721 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010722 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723}
10724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010725PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010726 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010727\n\
10728Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010729have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730
10731static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010732unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010733{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010734 if (PyUnicode_READY(self) == -1)
10735 return NULL;
10736 if (PyUnicode_GET_LENGTH(self) == 0)
10737 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010738 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739}
10740
Benjamin Petersond5890c82012-01-14 13:23:30 -050010741PyDoc_STRVAR(casefold__doc__,
10742 "S.casefold() -> str\n\
10743\n\
10744Return a version of S suitable for caseless comparisons.");
10745
10746static PyObject *
10747unicode_casefold(PyObject *self)
10748{
10749 if (PyUnicode_READY(self) == -1)
10750 return NULL;
10751 if (PyUnicode_IS_ASCII(self))
10752 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010753 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010754}
10755
10756
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010757/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010758
10759static int
10760convert_uc(PyObject *obj, void *addr)
10761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010763
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010764 if (!PyUnicode_Check(obj)) {
10765 PyErr_Format(PyExc_TypeError,
10766 "The fill character must be a unicode character, "
10767 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010768 return 0;
10769 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010770 if (PyUnicode_READY(obj) < 0)
10771 return 0;
10772 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010773 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010774 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010775 return 0;
10776 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010777 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010778 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010779}
10780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010781PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010782 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010784Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010785done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786
10787static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010788unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010790 Py_ssize_t marg, left;
10791 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 Py_UCS4 fillchar = ' ';
10793
Victor Stinnere9a29352011-10-01 02:14:59 +020010794 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796
Benjamin Petersonbac79492012-01-14 13:34:47 -050010797 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 return NULL;
10799
Victor Stinnerc4b49542011-12-11 22:44:26 +010010800 if (PyUnicode_GET_LENGTH(self) >= width)
10801 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802
Victor Stinnerc4b49542011-12-11 22:44:26 +010010803 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804 left = marg / 2 + (marg & width & 1);
10805
Victor Stinner9310abb2011-10-05 00:59:23 +020010806 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807}
10808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809/* This function assumes that str1 and str2 are readied by the caller. */
10810
Marc-André Lemburge5034372000-08-08 08:04:29 +000010811static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010812unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010813{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010814#define COMPARE(TYPE1, TYPE2) \
10815 do { \
10816 TYPE1* p1 = (TYPE1 *)data1; \
10817 TYPE2* p2 = (TYPE2 *)data2; \
10818 TYPE1* end = p1 + len; \
10819 Py_UCS4 c1, c2; \
10820 for (; p1 != end; p1++, p2++) { \
10821 c1 = *p1; \
10822 c2 = *p2; \
10823 if (c1 != c2) \
10824 return (c1 < c2) ? -1 : 1; \
10825 } \
10826 } \
10827 while (0)
10828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010829 int kind1, kind2;
10830 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010831 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010833 kind1 = PyUnicode_KIND(str1);
10834 kind2 = PyUnicode_KIND(str2);
10835 data1 = PyUnicode_DATA(str1);
10836 data2 = PyUnicode_DATA(str2);
10837 len1 = PyUnicode_GET_LENGTH(str1);
10838 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010839 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010840
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010841 switch(kind1) {
10842 case PyUnicode_1BYTE_KIND:
10843 {
10844 switch(kind2) {
10845 case PyUnicode_1BYTE_KIND:
10846 {
10847 int cmp = memcmp(data1, data2, len);
10848 /* normalize result of memcmp() into the range [-1; 1] */
10849 if (cmp < 0)
10850 return -1;
10851 if (cmp > 0)
10852 return 1;
10853 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010854 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010855 case PyUnicode_2BYTE_KIND:
10856 COMPARE(Py_UCS1, Py_UCS2);
10857 break;
10858 case PyUnicode_4BYTE_KIND:
10859 COMPARE(Py_UCS1, Py_UCS4);
10860 break;
10861 default:
10862 assert(0);
10863 }
10864 break;
10865 }
10866 case PyUnicode_2BYTE_KIND:
10867 {
10868 switch(kind2) {
10869 case PyUnicode_1BYTE_KIND:
10870 COMPARE(Py_UCS2, Py_UCS1);
10871 break;
10872 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010873 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010874 COMPARE(Py_UCS2, Py_UCS2);
10875 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010876 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010877 case PyUnicode_4BYTE_KIND:
10878 COMPARE(Py_UCS2, Py_UCS4);
10879 break;
10880 default:
10881 assert(0);
10882 }
10883 break;
10884 }
10885 case PyUnicode_4BYTE_KIND:
10886 {
10887 switch(kind2) {
10888 case PyUnicode_1BYTE_KIND:
10889 COMPARE(Py_UCS4, Py_UCS1);
10890 break;
10891 case PyUnicode_2BYTE_KIND:
10892 COMPARE(Py_UCS4, Py_UCS2);
10893 break;
10894 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010895 {
10896#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10897 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10898 /* normalize result of wmemcmp() into the range [-1; 1] */
10899 if (cmp < 0)
10900 return -1;
10901 if (cmp > 0)
10902 return 1;
10903#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010904 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010905#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010906 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010907 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010908 default:
10909 assert(0);
10910 }
10911 break;
10912 }
10913 default:
10914 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010915 }
10916
Victor Stinner770e19e2012-10-04 22:59:45 +020010917 if (len1 == len2)
10918 return 0;
10919 if (len1 < len2)
10920 return -1;
10921 else
10922 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010923
10924#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010925}
10926
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010927Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010928unicode_compare_eq(PyObject *str1, PyObject *str2)
10929{
10930 int kind;
10931 void *data1, *data2;
10932 Py_ssize_t len;
10933 int cmp;
10934
Victor Stinnere5567ad2012-10-23 02:48:49 +020010935 len = PyUnicode_GET_LENGTH(str1);
10936 if (PyUnicode_GET_LENGTH(str2) != len)
10937 return 0;
10938 kind = PyUnicode_KIND(str1);
10939 if (PyUnicode_KIND(str2) != kind)
10940 return 0;
10941 data1 = PyUnicode_DATA(str1);
10942 data2 = PyUnicode_DATA(str2);
10943
10944 cmp = memcmp(data1, data2, len * kind);
10945 return (cmp == 0);
10946}
10947
10948
Alexander Belopolsky40018472011-02-26 01:02:56 +000010949int
10950PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10953 if (PyUnicode_READY(left) == -1 ||
10954 PyUnicode_READY(right) == -1)
10955 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010956
10957 /* a string is equal to itself */
10958 if (left == right)
10959 return 0;
10960
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010961 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010963 PyErr_Format(PyExc_TypeError,
10964 "Can't compare %.100s and %.100s",
10965 left->ob_type->tp_name,
10966 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967 return -1;
10968}
10969
Martin v. Löwis5b222132007-06-10 09:51:05 +000010970int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010971_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10972{
10973 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10974 if (right_str == NULL)
10975 return -1;
10976 return PyUnicode_Compare(left, right_str);
10977}
10978
10979int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010980PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10981{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 Py_ssize_t i;
10983 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 Py_UCS4 chr;
10985
Victor Stinner910337b2011-10-03 03:20:16 +020010986 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 if (PyUnicode_READY(uni) == -1)
10988 return -1;
10989 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010990 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010991 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010992 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010993 size_t len, len2 = strlen(str);
10994 int cmp;
10995
10996 len = Py_MIN(len1, len2);
10997 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010998 if (cmp != 0) {
10999 if (cmp < 0)
11000 return -1;
11001 else
11002 return 1;
11003 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011004 if (len1 > len2)
11005 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011006 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011007 return -1; /* str is longer */
11008 return 0;
11009 }
11010 else {
11011 void *data = PyUnicode_DATA(uni);
11012 /* Compare Unicode string and source character set string */
11013 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011014 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011015 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11016 /* This check keeps Python strings that end in '\0' from comparing equal
11017 to C strings identical up to that point. */
11018 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11019 return 1; /* uni is longer */
11020 if (str[i])
11021 return -1; /* str is longer */
11022 return 0;
11023 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011024}
11025
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011026
Benjamin Peterson29060642009-01-31 22:14:21 +000011027#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011028 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011029
Alexander Belopolsky40018472011-02-26 01:02:56 +000011030PyObject *
11031PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011032{
11033 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011034 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011035
Victor Stinnere5567ad2012-10-23 02:48:49 +020011036 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11037 Py_RETURN_NOTIMPLEMENTED;
11038
11039 if (PyUnicode_READY(left) == -1 ||
11040 PyUnicode_READY(right) == -1)
11041 return NULL;
11042
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011043 if (left == right) {
11044 switch (op) {
11045 case Py_EQ:
11046 case Py_LE:
11047 case Py_GE:
11048 /* a string is equal to itself */
11049 v = Py_True;
11050 break;
11051 case Py_NE:
11052 case Py_LT:
11053 case Py_GT:
11054 v = Py_False;
11055 break;
11056 default:
11057 PyErr_BadArgument();
11058 return NULL;
11059 }
11060 }
11061 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011062 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011063 result ^= (op == Py_NE);
11064 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011065 }
11066 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011067 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011068
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011069 /* Convert the return value to a Boolean */
11070 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011071 case Py_LE:
11072 v = TEST_COND(result <= 0);
11073 break;
11074 case Py_GE:
11075 v = TEST_COND(result >= 0);
11076 break;
11077 case Py_LT:
11078 v = TEST_COND(result == -1);
11079 break;
11080 case Py_GT:
11081 v = TEST_COND(result == 1);
11082 break;
11083 default:
11084 PyErr_BadArgument();
11085 return NULL;
11086 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011087 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011088 Py_INCREF(v);
11089 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011090}
11091
Alexander Belopolsky40018472011-02-26 01:02:56 +000011092int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011093_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11094{
11095 return unicode_eq(aa, bb);
11096}
11097
11098int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011099PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011100{
Victor Stinner77282cb2013-04-14 19:22:47 +020011101 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011102 void *buf1, *buf2;
11103 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011104 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011105
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011106 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011107 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011108 "'in <string>' requires string as left operand, not %.100s",
11109 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011110 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011111 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011112 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011113 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011114 if (ensure_unicode(str) < 0)
11115 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011118 kind2 = PyUnicode_KIND(substr);
11119 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011120 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011121 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011122 len2 = PyUnicode_GET_LENGTH(substr);
11123 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011124 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011125 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011126 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011127 if (len2 == 1) {
11128 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11129 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011130 return result;
11131 }
11132 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011133 buf2 = _PyUnicode_AsKind(substr, kind1);
11134 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011135 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137
Victor Stinner77282cb2013-04-14 19:22:47 +020011138 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 case PyUnicode_1BYTE_KIND:
11140 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11141 break;
11142 case PyUnicode_2BYTE_KIND:
11143 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11144 break;
11145 case PyUnicode_4BYTE_KIND:
11146 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11147 break;
11148 default:
11149 result = -1;
11150 assert(0);
11151 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011152
Victor Stinner77282cb2013-04-14 19:22:47 +020011153 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154 PyMem_Free(buf2);
11155
Guido van Rossum403d68b2000-03-13 15:55:09 +000011156 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011157}
11158
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159/* Concat to string or Unicode object giving a new Unicode object. */
11160
Alexander Belopolsky40018472011-02-26 01:02:56 +000011161PyObject *
11162PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011164 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011165 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011166 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011168 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11169 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170
11171 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011172 if (left == unicode_empty)
11173 return PyUnicode_FromObject(right);
11174 if (right == unicode_empty)
11175 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011177 left_len = PyUnicode_GET_LENGTH(left);
11178 right_len = PyUnicode_GET_LENGTH(right);
11179 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011180 PyErr_SetString(PyExc_OverflowError,
11181 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011182 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011183 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011184 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011185
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011186 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11187 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011188 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011189
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011191 result = PyUnicode_New(new_len, maxchar);
11192 if (result == NULL)
11193 return NULL;
11194 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11195 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11196 assert(_PyUnicode_CheckConsistency(result, 1));
11197 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198}
11199
Walter Dörwald1ab83302007-05-18 17:15:44 +000011200void
Victor Stinner23e56682011-10-03 03:54:37 +020011201PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011202{
Victor Stinner23e56682011-10-03 03:54:37 +020011203 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011204 Py_UCS4 maxchar, maxchar2;
11205 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011206
11207 if (p_left == NULL) {
11208 if (!PyErr_Occurred())
11209 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011210 return;
11211 }
Victor Stinner23e56682011-10-03 03:54:37 +020011212 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011213 if (right == NULL || left == NULL
11214 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011215 if (!PyErr_Occurred())
11216 PyErr_BadInternalCall();
11217 goto error;
11218 }
11219
Benjamin Petersonbac79492012-01-14 13:34:47 -050011220 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011221 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011222 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011223 goto error;
11224
Victor Stinner488fa492011-12-12 00:01:39 +010011225 /* Shortcuts */
11226 if (left == unicode_empty) {
11227 Py_DECREF(left);
11228 Py_INCREF(right);
11229 *p_left = right;
11230 return;
11231 }
11232 if (right == unicode_empty)
11233 return;
11234
11235 left_len = PyUnicode_GET_LENGTH(left);
11236 right_len = PyUnicode_GET_LENGTH(right);
11237 if (left_len > PY_SSIZE_T_MAX - right_len) {
11238 PyErr_SetString(PyExc_OverflowError,
11239 "strings are too large to concat");
11240 goto error;
11241 }
11242 new_len = left_len + right_len;
11243
11244 if (unicode_modifiable(left)
11245 && PyUnicode_CheckExact(right)
11246 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011247 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11248 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011249 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011250 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011251 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11252 {
11253 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011254 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011255 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011256
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011257 /* copy 'right' into the newly allocated area of 'left' */
11258 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011259 }
Victor Stinner488fa492011-12-12 00:01:39 +010011260 else {
11261 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11262 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011263 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011264
Victor Stinner488fa492011-12-12 00:01:39 +010011265 /* Concat the two Unicode strings */
11266 res = PyUnicode_New(new_len, maxchar);
11267 if (res == NULL)
11268 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011269 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11270 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011271 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011272 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011273 }
11274 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011275 return;
11276
11277error:
Victor Stinner488fa492011-12-12 00:01:39 +010011278 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011279}
11280
11281void
11282PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11283{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011284 PyUnicode_Append(pleft, right);
11285 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011286}
11287
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011288/*
11289Wraps stringlib_parse_args_finds() and additionally ensures that the
11290first argument is a unicode object.
11291*/
11292
11293Py_LOCAL_INLINE(int)
11294parse_args_finds_unicode(const char * function_name, PyObject *args,
11295 PyObject **substring,
11296 Py_ssize_t *start, Py_ssize_t *end)
11297{
11298 if(stringlib_parse_args_finds(function_name, args, substring,
11299 start, end)) {
11300 if (ensure_unicode(*substring) < 0)
11301 return 0;
11302 return 1;
11303 }
11304 return 0;
11305}
11306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011307PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011308 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011310Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011311string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011312interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313
11314static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011315unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011317 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011318 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011319 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011321 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011322 void *buf1, *buf2;
11323 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011325 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 kind1 = PyUnicode_KIND(self);
11329 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011330 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011331 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 len1 = PyUnicode_GET_LENGTH(self);
11334 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011336 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011337 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011338
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011339 buf1 = PyUnicode_DATA(self);
11340 buf2 = PyUnicode_DATA(substring);
11341 if (kind2 != kind1) {
11342 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011343 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011344 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011345 }
11346 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 case PyUnicode_1BYTE_KIND:
11348 iresult = ucs1lib_count(
11349 ((Py_UCS1*)buf1) + start, end - start,
11350 buf2, len2, PY_SSIZE_T_MAX
11351 );
11352 break;
11353 case PyUnicode_2BYTE_KIND:
11354 iresult = ucs2lib_count(
11355 ((Py_UCS2*)buf1) + start, end - start,
11356 buf2, len2, PY_SSIZE_T_MAX
11357 );
11358 break;
11359 case PyUnicode_4BYTE_KIND:
11360 iresult = ucs4lib_count(
11361 ((Py_UCS4*)buf1) + start, end - start,
11362 buf2, len2, PY_SSIZE_T_MAX
11363 );
11364 break;
11365 default:
11366 assert(0); iresult = 0;
11367 }
11368
11369 result = PyLong_FromSsize_t(iresult);
11370
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011371 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374 return result;
11375}
11376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011378 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011380Encode S using the codec registered for encoding. Default encoding\n\
11381is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011382handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011383a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11384'xmlcharrefreplace' as well as any other name registered with\n\
11385codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386
11387static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011388unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011390 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 char *encoding = NULL;
11392 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011393
Benjamin Peterson308d6372009-09-18 21:42:35 +000011394 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11395 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011397 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011398}
11399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011400PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011401 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402\n\
11403Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011404If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405
11406static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011407unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011409 Py_ssize_t i, j, line_pos, src_len, incr;
11410 Py_UCS4 ch;
11411 PyObject *u;
11412 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011413 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011415 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011416 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
Ezio Melotti745d54d2013-11-16 19:10:57 +020011418 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11419 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
Antoine Pitrou22425222011-10-04 19:10:51 +020011422 if (PyUnicode_READY(self) == -1)
11423 return NULL;
11424
Thomas Wouters7e474022000-07-16 12:04:32 +000011425 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011426 src_len = PyUnicode_GET_LENGTH(self);
11427 i = j = line_pos = 0;
11428 kind = PyUnicode_KIND(self);
11429 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011430 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011431 for (; i < src_len; i++) {
11432 ch = PyUnicode_READ(kind, src_data, i);
11433 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011434 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011435 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011436 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 goto overflow;
11439 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011440 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011441 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011445 goto overflow;
11446 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011448 if (ch == '\n' || ch == '\r')
11449 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011451 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011452 if (!found)
11453 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011454
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011456 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 if (!u)
11458 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011459 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 for (; i < src_len; i++) {
11464 ch = PyUnicode_READ(kind, src_data, i);
11465 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011466 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011467 incr = tabsize - (line_pos % tabsize);
11468 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011469 FILL(kind, dest_data, ' ', j, incr);
11470 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011472 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011474 line_pos++;
11475 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011476 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011477 if (ch == '\n' || ch == '\r')
11478 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011480 }
11481 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011482 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011483
Antoine Pitroue71d5742011-10-04 15:55:09 +020011484 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011485 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11486 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487}
11488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011489PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491\n\
11492Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011493such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494arguments start and end are interpreted as in slice notation.\n\
11495\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
11498static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011501 /* initialize variables to prevent gcc warning */
11502 PyObject *substring = NULL;
11503 Py_ssize_t start = 0;
11504 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011505 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011507 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011510 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011513 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 if (result == -2)
11516 return NULL;
11517
Christian Heimes217cfd12007-12-02 14:31:20 +000011518 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519}
11520
11521static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011522unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011524 void *data;
11525 enum PyUnicode_Kind kind;
11526 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011527
11528 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11529 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011531 }
11532 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11533 PyErr_SetString(PyExc_IndexError, "string index out of range");
11534 return NULL;
11535 }
11536 kind = PyUnicode_KIND(self);
11537 data = PyUnicode_DATA(self);
11538 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011539 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540}
11541
Guido van Rossumc2504932007-09-18 19:42:40 +000011542/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011543 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011544static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011545unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546{
Guido van Rossumc2504932007-09-18 19:42:40 +000011547 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011548 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011549
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011550#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011551 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011552#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 if (_PyUnicode_HASH(self) != -1)
11554 return _PyUnicode_HASH(self);
11555 if (PyUnicode_READY(self) == -1)
11556 return -1;
11557 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011558 /*
11559 We make the hash of the empty string be 0, rather than using
11560 (prefix ^ suffix), since this slightly obfuscates the hash secret
11561 */
11562 if (len == 0) {
11563 _PyUnicode_HASH(self) = 0;
11564 return 0;
11565 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011566 x = _Py_HashBytes(PyUnicode_DATA(self),
11567 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011569 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570}
11571
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011572PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011573 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011575Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
11577static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011580 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011581 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011582 PyObject *substring = NULL;
11583 Py_ssize_t start = 0;
11584 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011586 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011589 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011592 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 if (result == -2)
11595 return NULL;
11596
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597 if (result < 0) {
11598 PyErr_SetString(PyExc_ValueError, "substring not found");
11599 return NULL;
11600 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011601
Christian Heimes217cfd12007-12-02 14:31:20 +000011602 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603}
11604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011605PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011606 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011608Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011609at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
11611static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011612unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 Py_ssize_t i, length;
11615 int kind;
11616 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617 int cased;
11618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (PyUnicode_READY(self) == -1)
11620 return NULL;
11621 length = PyUnicode_GET_LENGTH(self);
11622 kind = PyUnicode_KIND(self);
11623 data = PyUnicode_DATA(self);
11624
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 if (length == 1)
11627 return PyBool_FromLong(
11628 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011630 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011632 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011633
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011635 for (i = 0; i < length; i++) {
11636 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011637
Benjamin Peterson29060642009-01-31 22:14:21 +000011638 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11639 return PyBool_FromLong(0);
11640 else if (!cased && Py_UNICODE_ISLOWER(ch))
11641 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011643 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644}
11645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011646PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011647 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011648\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011649Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011650at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651
11652static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011653unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655 Py_ssize_t i, length;
11656 int kind;
11657 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011658 int cased;
11659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 if (PyUnicode_READY(self) == -1)
11661 return NULL;
11662 length = PyUnicode_GET_LENGTH(self);
11663 kind = PyUnicode_KIND(self);
11664 data = PyUnicode_DATA(self);
11665
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 if (length == 1)
11668 return PyBool_FromLong(
11669 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011671 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011673 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011674
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 for (i = 0; i < length; i++) {
11677 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011678
Benjamin Peterson29060642009-01-31 22:14:21 +000011679 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11680 return PyBool_FromLong(0);
11681 else if (!cased && Py_UNICODE_ISUPPER(ch))
11682 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011684 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685}
11686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011687PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011690Return True if S is a titlecased string and there is at least one\n\
11691character in S, i.e. upper- and titlecase characters may only\n\
11692follow uncased characters and lowercase characters only cased ones.\n\
11693Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694
11695static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011696unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 Py_ssize_t i, length;
11699 int kind;
11700 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701 int cased, previous_is_cased;
11702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011703 if (PyUnicode_READY(self) == -1)
11704 return NULL;
11705 length = PyUnicode_GET_LENGTH(self);
11706 kind = PyUnicode_KIND(self);
11707 data = PyUnicode_DATA(self);
11708
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 if (length == 1) {
11711 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11712 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11713 (Py_UNICODE_ISUPPER(ch) != 0));
11714 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011716 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011718 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011719
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720 cased = 0;
11721 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 for (i = 0; i < length; i++) {
11723 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011724
Benjamin Peterson29060642009-01-31 22:14:21 +000011725 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11726 if (previous_is_cased)
11727 return PyBool_FromLong(0);
11728 previous_is_cased = 1;
11729 cased = 1;
11730 }
11731 else if (Py_UNICODE_ISLOWER(ch)) {
11732 if (!previous_is_cased)
11733 return PyBool_FromLong(0);
11734 previous_is_cased = 1;
11735 cased = 1;
11736 }
11737 else
11738 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011740 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741}
11742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011743PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011744 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011746Return True if all characters in S are whitespace\n\
11747and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748
11749static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011750unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 Py_ssize_t i, length;
11753 int kind;
11754 void *data;
11755
11756 if (PyUnicode_READY(self) == -1)
11757 return NULL;
11758 length = PyUnicode_GET_LENGTH(self);
11759 kind = PyUnicode_KIND(self);
11760 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 if (length == 1)
11764 return PyBool_FromLong(
11765 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011767 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011769 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 for (i = 0; i < length; i++) {
11772 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011773 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011774 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011776 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777}
11778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011779PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011780 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011781\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011782Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011783and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011784
11785static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011786unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011787{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011788 Py_ssize_t i, length;
11789 int kind;
11790 void *data;
11791
11792 if (PyUnicode_READY(self) == -1)
11793 return NULL;
11794 length = PyUnicode_GET_LENGTH(self);
11795 kind = PyUnicode_KIND(self);
11796 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011797
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011798 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 if (length == 1)
11800 return PyBool_FromLong(
11801 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011802
11803 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011805 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 for (i = 0; i < length; i++) {
11808 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011809 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011810 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011811 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011812}
11813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011814PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011815 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011816\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011817Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011818and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011819
11820static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011821unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011822{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 int kind;
11824 void *data;
11825 Py_ssize_t len, i;
11826
11827 if (PyUnicode_READY(self) == -1)
11828 return NULL;
11829
11830 kind = PyUnicode_KIND(self);
11831 data = PyUnicode_DATA(self);
11832 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011833
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011834 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 if (len == 1) {
11836 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11837 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11838 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011839
11840 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011842 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011844 for (i = 0; i < len; i++) {
11845 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011846 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011847 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011848 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011849 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850}
11851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011852PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011853 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011855Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011856False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857
11858static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011859unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 Py_ssize_t i, length;
11862 int kind;
11863 void *data;
11864
11865 if (PyUnicode_READY(self) == -1)
11866 return NULL;
11867 length = PyUnicode_GET_LENGTH(self);
11868 kind = PyUnicode_KIND(self);
11869 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 if (length == 1)
11873 return PyBool_FromLong(
11874 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011876 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 for (i = 0; i < length; i++) {
11881 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011884 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885}
11886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011887PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011890Return True if all characters in S are digits\n\
11891and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892
11893static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011894unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 Py_ssize_t i, length;
11897 int kind;
11898 void *data;
11899
11900 if (PyUnicode_READY(self) == -1)
11901 return NULL;
11902 length = PyUnicode_GET_LENGTH(self);
11903 kind = PyUnicode_KIND(self);
11904 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (length == 1) {
11908 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11909 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11910 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011912 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 for (i = 0; i < length; i++) {
11917 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011918 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011920 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921}
11922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011923PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011924 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011925\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011926Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011927False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928
11929static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011930unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 Py_ssize_t i, length;
11933 int kind;
11934 void *data;
11935
11936 if (PyUnicode_READY(self) == -1)
11937 return NULL;
11938 length = PyUnicode_GET_LENGTH(self);
11939 kind = PyUnicode_KIND(self);
11940 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 if (length == 1)
11944 return PyBool_FromLong(
11945 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011947 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011949 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 for (i = 0; i < length; i++) {
11952 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011953 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011955 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956}
11957
Martin v. Löwis47383402007-08-15 07:32:56 +000011958int
11959PyUnicode_IsIdentifier(PyObject *self)
11960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 int kind;
11962 void *data;
11963 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011964 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 if (PyUnicode_READY(self) == -1) {
11967 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011968 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 }
11970
11971 /* Special case for empty strings */
11972 if (PyUnicode_GET_LENGTH(self) == 0)
11973 return 0;
11974 kind = PyUnicode_KIND(self);
11975 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011976
11977 /* PEP 3131 says that the first character must be in
11978 XID_Start and subsequent characters in XID_Continue,
11979 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011980 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011981 letters, digits, underscore). However, given the current
11982 definition of XID_Start and XID_Continue, it is sufficient
11983 to check just for these, except that _ must be allowed
11984 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011986 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011987 return 0;
11988
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011989 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011991 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011992 return 1;
11993}
11994
11995PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011996 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011997\n\
11998Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011999to the language definition.\n\
12000\n\
12001Use keyword.iskeyword() to test for reserved identifiers\n\
12002such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012003
12004static PyObject*
12005unicode_isidentifier(PyObject *self)
12006{
12007 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12008}
12009
Georg Brandl559e5d72008-06-11 18:37:52 +000012010PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012011 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012012\n\
12013Return True if all characters in S are considered\n\
12014printable in repr() or S is empty, False otherwise.");
12015
12016static PyObject*
12017unicode_isprintable(PyObject *self)
12018{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 Py_ssize_t i, length;
12020 int kind;
12021 void *data;
12022
12023 if (PyUnicode_READY(self) == -1)
12024 return NULL;
12025 length = PyUnicode_GET_LENGTH(self);
12026 kind = PyUnicode_KIND(self);
12027 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012028
12029 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 if (length == 1)
12031 return PyBool_FromLong(
12032 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 for (i = 0; i < length; i++) {
12035 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012036 Py_RETURN_FALSE;
12037 }
12038 }
12039 Py_RETURN_TRUE;
12040}
12041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012042PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012043 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012044\n\
12045Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012046iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047
12048static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012049unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012051 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052}
12053
Martin v. Löwis18e16552006-02-15 17:27:45 +000012054static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012055unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 if (PyUnicode_READY(self) == -1)
12058 return -1;
12059 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060}
12061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012062PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012063 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012065Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012066done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067
12068static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012069unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012070{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012071 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012072 Py_UCS4 fillchar = ' ';
12073
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012074 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075 return NULL;
12076
Benjamin Petersonbac79492012-01-14 13:34:47 -050012077 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012078 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
Victor Stinnerc4b49542011-12-11 22:44:26 +010012080 if (PyUnicode_GET_LENGTH(self) >= width)
12081 return unicode_result_unchanged(self);
12082
12083 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084}
12085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012086PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012087 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012088\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012089Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090
12091static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012092unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012094 if (PyUnicode_READY(self) == -1)
12095 return NULL;
12096 if (PyUnicode_IS_ASCII(self))
12097 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012098 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099}
12100
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012101#define LEFTSTRIP 0
12102#define RIGHTSTRIP 1
12103#define BOTHSTRIP 2
12104
12105/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012106static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012107
12108#define STRIPNAME(i) (stripformat[i]+3)
12109
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012110/* externally visible for str.strip(unicode) */
12111PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012112_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012113{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 void *data;
12115 int kind;
12116 Py_ssize_t i, j, len;
12117 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012118 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12121 return NULL;
12122
12123 kind = PyUnicode_KIND(self);
12124 data = PyUnicode_DATA(self);
12125 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012126 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12128 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012129 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012130
Benjamin Peterson14339b62009-01-31 16:36:08 +000012131 i = 0;
12132 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012133 while (i < len) {
12134 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12135 if (!BLOOM(sepmask, ch))
12136 break;
12137 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12138 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012139 i++;
12140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012141 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012142
Benjamin Peterson14339b62009-01-31 16:36:08 +000012143 j = len;
12144 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012145 j--;
12146 while (j >= i) {
12147 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12148 if (!BLOOM(sepmask, ch))
12149 break;
12150 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12151 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012152 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012153 }
12154
Benjamin Peterson29060642009-01-31 22:14:21 +000012155 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012156 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012157
Victor Stinner7931d9a2011-11-04 00:22:48 +010012158 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159}
12160
12161PyObject*
12162PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12163{
12164 unsigned char *data;
12165 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012166 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167
Victor Stinnerde636f32011-10-01 03:55:54 +020012168 if (PyUnicode_READY(self) == -1)
12169 return NULL;
12170
Victor Stinner684d5fd2012-05-03 02:32:34 +020012171 length = PyUnicode_GET_LENGTH(self);
12172 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012173
Victor Stinner684d5fd2012-05-03 02:32:34 +020012174 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012175 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176
Victor Stinnerde636f32011-10-01 03:55:54 +020012177 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012178 PyErr_SetString(PyExc_IndexError, "string index out of range");
12179 return NULL;
12180 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012181 if (start >= length || end < start)
12182 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012183
Victor Stinner684d5fd2012-05-03 02:32:34 +020012184 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012185 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012186 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012187 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012188 }
12189 else {
12190 kind = PyUnicode_KIND(self);
12191 data = PyUnicode_1BYTE_DATA(self);
12192 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012193 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012194 length);
12195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012196}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197
12198static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012199do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 Py_ssize_t len, i, j;
12202
12203 if (PyUnicode_READY(self) == -1)
12204 return NULL;
12205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012207
Victor Stinnercc7af722013-04-09 22:39:24 +020012208 if (PyUnicode_IS_ASCII(self)) {
12209 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12210
12211 i = 0;
12212 if (striptype != RIGHTSTRIP) {
12213 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012214 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012215 if (!_Py_ascii_whitespace[ch])
12216 break;
12217 i++;
12218 }
12219 }
12220
12221 j = len;
12222 if (striptype != LEFTSTRIP) {
12223 j--;
12224 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012225 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012226 if (!_Py_ascii_whitespace[ch])
12227 break;
12228 j--;
12229 }
12230 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012231 }
12232 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012233 else {
12234 int kind = PyUnicode_KIND(self);
12235 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012236
Victor Stinnercc7af722013-04-09 22:39:24 +020012237 i = 0;
12238 if (striptype != RIGHTSTRIP) {
12239 while (i < len) {
12240 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12241 if (!Py_UNICODE_ISSPACE(ch))
12242 break;
12243 i++;
12244 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012245 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012246
12247 j = len;
12248 if (striptype != LEFTSTRIP) {
12249 j--;
12250 while (j >= i) {
12251 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12252 if (!Py_UNICODE_ISSPACE(ch))
12253 break;
12254 j--;
12255 }
12256 j++;
12257 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012258 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012259
Victor Stinner7931d9a2011-11-04 00:22:48 +010012260 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261}
12262
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012263
12264static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012265do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012266{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012267 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012268
Serhiy Storchakac6792272013-10-19 21:03:34 +030012269 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012270 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012271
Benjamin Peterson14339b62009-01-31 16:36:08 +000012272 if (sep != NULL && sep != Py_None) {
12273 if (PyUnicode_Check(sep))
12274 return _PyUnicode_XStrip(self, striptype, sep);
12275 else {
12276 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012277 "%s arg must be None or str",
12278 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012279 return NULL;
12280 }
12281 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012282
Benjamin Peterson14339b62009-01-31 16:36:08 +000012283 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012284}
12285
12286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012287PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012288 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012289\n\
12290Return a copy of the string S with leading and trailing\n\
12291whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012292If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012293
12294static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012295unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012296{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012297 if (PyTuple_GET_SIZE(args) == 0)
12298 return do_strip(self, BOTHSTRIP); /* Common case */
12299 else
12300 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012301}
12302
12303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012304PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012305 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012306\n\
12307Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012308If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012309
12310static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012311unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012312{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012313 if (PyTuple_GET_SIZE(args) == 0)
12314 return do_strip(self, LEFTSTRIP); /* Common case */
12315 else
12316 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012317}
12318
12319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012320PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012322\n\
12323Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012324If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012325
12326static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012327unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012328{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012329 if (PyTuple_GET_SIZE(args) == 0)
12330 return do_strip(self, RIGHTSTRIP); /* Common case */
12331 else
12332 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012333}
12334
12335
Guido van Rossumd57fd912000-03-10 22:53:23 +000012336static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012337unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012339 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341
Serhiy Storchaka05997252013-01-26 12:14:02 +020012342 if (len < 1)
12343 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344
Victor Stinnerc4b49542011-12-11 22:44:26 +010012345 /* no repeat, return original string */
12346 if (len == 1)
12347 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012348
Benjamin Petersonbac79492012-01-14 13:34:47 -050012349 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 return NULL;
12351
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012352 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012353 PyErr_SetString(PyExc_OverflowError,
12354 "repeated string is too long");
12355 return NULL;
12356 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012358
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012359 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360 if (!u)
12361 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012362 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 if (PyUnicode_GET_LENGTH(str) == 1) {
12365 const int kind = PyUnicode_KIND(str);
12366 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012367 if (kind == PyUnicode_1BYTE_KIND) {
12368 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012369 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012370 }
12371 else if (kind == PyUnicode_2BYTE_KIND) {
12372 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012373 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012374 ucs2[n] = fill_char;
12375 } else {
12376 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12377 assert(kind == PyUnicode_4BYTE_KIND);
12378 for (n = 0; n < len; ++n)
12379 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381 }
12382 else {
12383 /* number of characters copied this far */
12384 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012385 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386 char *to = (char *) PyUnicode_DATA(u);
12387 Py_MEMCPY(to, PyUnicode_DATA(str),
12388 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012389 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390 n = (done <= nchars-done) ? done : nchars-done;
12391 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012392 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012393 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394 }
12395
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012396 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012397 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012398}
12399
Alexander Belopolsky40018472011-02-26 01:02:56 +000012400PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012401PyUnicode_Replace(PyObject *str,
12402 PyObject *substr,
12403 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012404 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012405{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012406 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12407 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012408 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012409 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012410}
12411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012412PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012413 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012414\n\
12415Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012416old replaced by new. If the optional argument count is\n\
12417given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012418
12419static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422 PyObject *str1;
12423 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012424 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012425
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012426 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012428 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012429 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012430 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012431}
12432
Alexander Belopolsky40018472011-02-26 01:02:56 +000012433static PyObject *
12434unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012435{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012436 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437 Py_ssize_t isize;
12438 Py_ssize_t osize, squote, dquote, i, o;
12439 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012440 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012444 return NULL;
12445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012446 isize = PyUnicode_GET_LENGTH(unicode);
12447 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012448
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 /* Compute length of output, quote characters, and
12450 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012451 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012452 max = 127;
12453 squote = dquote = 0;
12454 ikind = PyUnicode_KIND(unicode);
12455 for (i = 0; i < isize; i++) {
12456 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012457 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012459 case '\'': squote++; break;
12460 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012461 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012462 incr = 2;
12463 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464 default:
12465 /* Fast-path ASCII */
12466 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012467 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012468 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012469 ;
12470 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012473 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012474 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012475 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012477 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012479 if (osize > PY_SSIZE_T_MAX - incr) {
12480 PyErr_SetString(PyExc_OverflowError,
12481 "string is too long to generate repr");
12482 return NULL;
12483 }
12484 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485 }
12486
12487 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012488 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012489 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012490 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 if (dquote)
12492 /* Both squote and dquote present. Use squote,
12493 and escape them */
12494 osize += squote;
12495 else
12496 quote = '"';
12497 }
Victor Stinner55c08782013-04-14 18:45:39 +020012498 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012499
12500 repr = PyUnicode_New(osize, max);
12501 if (repr == NULL)
12502 return NULL;
12503 okind = PyUnicode_KIND(repr);
12504 odata = PyUnicode_DATA(repr);
12505
12506 PyUnicode_WRITE(okind, odata, 0, quote);
12507 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012508 if (unchanged) {
12509 _PyUnicode_FastCopyCharacters(repr, 1,
12510 unicode, 0,
12511 isize);
12512 }
12513 else {
12514 for (i = 0, o = 1; i < isize; i++) {
12515 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012516
Victor Stinner55c08782013-04-14 18:45:39 +020012517 /* Escape quotes and backslashes */
12518 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012519 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012520 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012521 continue;
12522 }
12523
12524 /* Map special whitespace to '\t', \n', '\r' */
12525 if (ch == '\t') {
12526 PyUnicode_WRITE(okind, odata, o++, '\\');
12527 PyUnicode_WRITE(okind, odata, o++, 't');
12528 }
12529 else if (ch == '\n') {
12530 PyUnicode_WRITE(okind, odata, o++, '\\');
12531 PyUnicode_WRITE(okind, odata, o++, 'n');
12532 }
12533 else if (ch == '\r') {
12534 PyUnicode_WRITE(okind, odata, o++, '\\');
12535 PyUnicode_WRITE(okind, odata, o++, 'r');
12536 }
12537
12538 /* Map non-printable US ASCII to '\xhh' */
12539 else if (ch < ' ' || ch == 0x7F) {
12540 PyUnicode_WRITE(okind, odata, o++, '\\');
12541 PyUnicode_WRITE(okind, odata, o++, 'x');
12542 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12543 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12544 }
12545
12546 /* Copy ASCII characters as-is */
12547 else if (ch < 0x7F) {
12548 PyUnicode_WRITE(okind, odata, o++, ch);
12549 }
12550
12551 /* Non-ASCII characters */
12552 else {
12553 /* Map Unicode whitespace and control characters
12554 (categories Z* and C* except ASCII space)
12555 */
12556 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12557 PyUnicode_WRITE(okind, odata, o++, '\\');
12558 /* Map 8-bit characters to '\xhh' */
12559 if (ch <= 0xff) {
12560 PyUnicode_WRITE(okind, odata, o++, 'x');
12561 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12562 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12563 }
12564 /* Map 16-bit characters to '\uxxxx' */
12565 else if (ch <= 0xffff) {
12566 PyUnicode_WRITE(okind, odata, o++, 'u');
12567 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12568 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12569 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12570 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12571 }
12572 /* Map 21-bit characters to '\U00xxxxxx' */
12573 else {
12574 PyUnicode_WRITE(okind, odata, o++, 'U');
12575 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12576 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12577 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12578 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12579 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12580 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12581 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12582 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12583 }
12584 }
12585 /* Copy characters as-is */
12586 else {
12587 PyUnicode_WRITE(okind, odata, o++, ch);
12588 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012589 }
12590 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012593 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012594 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595}
12596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012597PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012598 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599\n\
12600Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012601such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602arguments start and end are interpreted as in slice notation.\n\
12603\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012604Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605
12606static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012609 /* initialize variables to prevent gcc warning */
12610 PyObject *substring = NULL;
12611 Py_ssize_t start = 0;
12612 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012613 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012615 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012616 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012618 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012619 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012621 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 if (result == -2)
12624 return NULL;
12625
Christian Heimes217cfd12007-12-02 14:31:20 +000012626 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627}
12628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012629PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012630 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012632Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633
12634static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012637 /* initialize variables to prevent gcc warning */
12638 PyObject *substring = NULL;
12639 Py_ssize_t start = 0;
12640 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012641 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012643 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012644 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012646 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012648
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012649 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 if (result == -2)
12652 return NULL;
12653
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654 if (result < 0) {
12655 PyErr_SetString(PyExc_ValueError, "substring not found");
12656 return NULL;
12657 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658
Christian Heimes217cfd12007-12-02 14:31:20 +000012659 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660}
12661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012662PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012663 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012665Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012666done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667
12668static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012669unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012671 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012672 Py_UCS4 fillchar = ' ';
12673
Victor Stinnere9a29352011-10-01 02:14:59 +020012674 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012676
Benjamin Petersonbac79492012-01-14 13:34:47 -050012677 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678 return NULL;
12679
Victor Stinnerc4b49542011-12-11 22:44:26 +010012680 if (PyUnicode_GET_LENGTH(self) >= width)
12681 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682
Victor Stinnerc4b49542011-12-11 22:44:26 +010012683 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684}
12685
Alexander Belopolsky40018472011-02-26 01:02:56 +000012686PyObject *
12687PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012689 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012690 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012692 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693}
12694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012695PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012696 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697\n\
12698Return a list of the words in S, using sep as the\n\
12699delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012700splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012701whitespace string is a separator and empty strings are\n\
12702removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703
12704static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012705unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012707 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012709 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012711 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12712 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713 return NULL;
12714
12715 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012716 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012717
12718 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012719 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012720
12721 PyErr_Format(PyExc_TypeError,
12722 "must be str or None, not %.100s",
12723 Py_TYPE(substring)->tp_name);
12724 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725}
12726
Thomas Wouters477c8d52006-05-27 19:21:47 +000012727PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012728PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012729{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012730 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012731 int kind1, kind2;
12732 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012733 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012734
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012735 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012736 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012737
Victor Stinner14f8f022011-10-05 20:58:25 +020012738 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012739 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 len1 = PyUnicode_GET_LENGTH(str_obj);
12741 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012742 if (kind1 < kind2 || len1 < len2) {
12743 _Py_INCREF_UNICODE_EMPTY();
12744 if (!unicode_empty)
12745 out = NULL;
12746 else {
12747 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12748 Py_DECREF(unicode_empty);
12749 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012750 return out;
12751 }
12752 buf1 = PyUnicode_DATA(str_obj);
12753 buf2 = PyUnicode_DATA(sep_obj);
12754 if (kind2 != kind1) {
12755 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12756 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012757 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012760 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012762 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12763 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12764 else
12765 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766 break;
12767 case PyUnicode_2BYTE_KIND:
12768 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12769 break;
12770 case PyUnicode_4BYTE_KIND:
12771 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12772 break;
12773 default:
12774 assert(0);
12775 out = 0;
12776 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012777
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012778 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012779 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012780
12781 return out;
12782}
12783
12784
12785PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012786PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012787{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012788 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012789 int kind1, kind2;
12790 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012792
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012793 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012794 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012795
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012796 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012797 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012798 len1 = PyUnicode_GET_LENGTH(str_obj);
12799 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012800 if (kind1 < kind2 || len1 < len2) {
12801 _Py_INCREF_UNICODE_EMPTY();
12802 if (!unicode_empty)
12803 out = NULL;
12804 else {
12805 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12806 Py_DECREF(unicode_empty);
12807 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012808 return out;
12809 }
12810 buf1 = PyUnicode_DATA(str_obj);
12811 buf2 = PyUnicode_DATA(sep_obj);
12812 if (kind2 != kind1) {
12813 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12814 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012815 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012816 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012817
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012818 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012819 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012820 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12821 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12822 else
12823 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012824 break;
12825 case PyUnicode_2BYTE_KIND:
12826 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12827 break;
12828 case PyUnicode_4BYTE_KIND:
12829 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12830 break;
12831 default:
12832 assert(0);
12833 out = 0;
12834 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012835
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012836 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012837 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012838
12839 return out;
12840}
12841
12842PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012843 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012844\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012845Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012847found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012848
12849static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012850unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012851{
Victor Stinner9310abb2011-10-05 00:59:23 +020012852 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853}
12854
12855PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012856 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012858Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012859the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012860separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012861
12862static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012863unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012864{
Victor Stinner9310abb2011-10-05 00:59:23 +020012865 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012866}
12867
Alexander Belopolsky40018472011-02-26 01:02:56 +000012868PyObject *
12869PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012870{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012871 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012872 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012873
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012874 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012875}
12876
12877PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012878 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012879\n\
12880Return a list of the words in S, using sep as the\n\
12881delimiter string, starting at the end of the string and\n\
12882working to the front. If maxsplit is given, at most maxsplit\n\
12883splits are done. If sep is not specified, any whitespace string\n\
12884is a separator.");
12885
12886static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012887unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012888{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012889 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012890 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012891 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012892
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012893 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12894 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012895 return NULL;
12896
12897 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012899
12900 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012901 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012902
12903 PyErr_Format(PyExc_TypeError,
12904 "must be str or None, not %.100s",
12905 Py_TYPE(substring)->tp_name);
12906 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012907}
12908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012909PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012911\n\
12912Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012913Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012914is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012915
12916static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012917unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012919 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012920 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012921
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012922 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12923 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012924 return NULL;
12925
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012926 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012927}
12928
12929static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012930PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012931{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012932 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933}
12934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012935PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012936 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012937\n\
12938Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012939and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012940
12941static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012942unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012943{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012944 if (PyUnicode_READY(self) == -1)
12945 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012946 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012947}
12948
Larry Hastings61272b72014-01-07 12:41:53 -080012949/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012950
Larry Hastings31826802013-10-19 00:09:25 -070012951@staticmethod
12952str.maketrans as unicode_maketrans
12953
12954 x: object
12955
12956 y: unicode=NULL
12957
12958 z: unicode=NULL
12959
12960 /
12961
12962Return a translation table usable for str.translate().
12963
12964If there is only one argument, it must be a dictionary mapping Unicode
12965ordinals (integers) or characters to Unicode ordinals, strings or None.
12966Character keys will be then converted to ordinals.
12967If there are two arguments, they must be strings of equal length, and
12968in the resulting dictionary, each character in x will be mapped to the
12969character at the same position in y. If there is a third argument, it
12970must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012971[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012972
Larry Hastings31826802013-10-19 00:09:25 -070012973static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012974unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012975/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012976{
Georg Brandlceee0772007-11-27 23:48:05 +000012977 PyObject *new = NULL, *key, *value;
12978 Py_ssize_t i = 0;
12979 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012980
Georg Brandlceee0772007-11-27 23:48:05 +000012981 new = PyDict_New();
12982 if (!new)
12983 return NULL;
12984 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 int x_kind, y_kind, z_kind;
12986 void *x_data, *y_data, *z_data;
12987
Georg Brandlceee0772007-11-27 23:48:05 +000012988 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012989 if (!PyUnicode_Check(x)) {
12990 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12991 "be a string if there is a second argument");
12992 goto err;
12993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012995 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12996 "arguments must have equal length");
12997 goto err;
12998 }
12999 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 x_kind = PyUnicode_KIND(x);
13001 y_kind = PyUnicode_KIND(y);
13002 x_data = PyUnicode_DATA(x);
13003 y_data = PyUnicode_DATA(y);
13004 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13005 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013006 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013007 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013008 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013009 if (!value) {
13010 Py_DECREF(key);
13011 goto err;
13012 }
Georg Brandlceee0772007-11-27 23:48:05 +000013013 res = PyDict_SetItem(new, key, value);
13014 Py_DECREF(key);
13015 Py_DECREF(value);
13016 if (res < 0)
13017 goto err;
13018 }
13019 /* create entries for deleting chars in z */
13020 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021 z_kind = PyUnicode_KIND(z);
13022 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013023 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013024 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013025 if (!key)
13026 goto err;
13027 res = PyDict_SetItem(new, key, Py_None);
13028 Py_DECREF(key);
13029 if (res < 0)
13030 goto err;
13031 }
13032 }
13033 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 int kind;
13035 void *data;
13036
Georg Brandlceee0772007-11-27 23:48:05 +000013037 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013038 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013039 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13040 "to maketrans it must be a dict");
13041 goto err;
13042 }
13043 /* copy entries into the new dict, converting string keys to int keys */
13044 while (PyDict_Next(x, &i, &key, &value)) {
13045 if (PyUnicode_Check(key)) {
13046 /* convert string keys to integer keys */
13047 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013048 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013049 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13050 "table must be of length 1");
13051 goto err;
13052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013053 kind = PyUnicode_KIND(key);
13054 data = PyUnicode_DATA(key);
13055 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013056 if (!newkey)
13057 goto err;
13058 res = PyDict_SetItem(new, newkey, value);
13059 Py_DECREF(newkey);
13060 if (res < 0)
13061 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013062 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013063 /* just keep integer keys */
13064 if (PyDict_SetItem(new, key, value) < 0)
13065 goto err;
13066 } else {
13067 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13068 "be strings or integers");
13069 goto err;
13070 }
13071 }
13072 }
13073 return new;
13074 err:
13075 Py_DECREF(new);
13076 return NULL;
13077}
13078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013079PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013080 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013081\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013082Return a copy of the string S in which each character has been mapped\n\
13083through the given translation table. The table must implement\n\
13084lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13085mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13086this operation raises LookupError, the character is left untouched.\n\
13087Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088
13089static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013090unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093}
13094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013095PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013098Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099
13100static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013101unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013103 if (PyUnicode_READY(self) == -1)
13104 return NULL;
13105 if (PyUnicode_IS_ASCII(self))
13106 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013107 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108}
13109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013110PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013113Pad a numeric string S with zeros on the left, to fill a field\n\
13114of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115
13116static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013117unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013118{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013119 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013120 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013121 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013122 int kind;
13123 void *data;
13124 Py_UCS4 chr;
13125
Martin v. Löwis18e16552006-02-15 17:27:45 +000013126 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127 return NULL;
13128
Benjamin Petersonbac79492012-01-14 13:34:47 -050013129 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013130 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131
Victor Stinnerc4b49542011-12-11 22:44:26 +010013132 if (PyUnicode_GET_LENGTH(self) >= width)
13133 return unicode_result_unchanged(self);
13134
13135 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136
13137 u = pad(self, fill, 0, '0');
13138
Walter Dörwald068325e2002-04-15 13:36:47 +000013139 if (u == NULL)
13140 return NULL;
13141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 kind = PyUnicode_KIND(u);
13143 data = PyUnicode_DATA(u);
13144 chr = PyUnicode_READ(kind, data, fill);
13145
13146 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013148 PyUnicode_WRITE(kind, data, 0, chr);
13149 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013150 }
13151
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013152 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013153 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013155
13156#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013157static PyObject *
13158unicode__decimal2ascii(PyObject *self)
13159{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013161}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162#endif
13163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013164PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013167Return True if S starts with the specified prefix, False otherwise.\n\
13168With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013169With optional end, stop comparing S at that position.\n\
13170prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171
13172static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013173unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013176 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013177 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013178 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013179 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181
Jesus Ceaac451502011-04-20 17:09:23 +020013182 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013183 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013184 if (PyTuple_Check(subobj)) {
13185 Py_ssize_t i;
13186 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013187 substring = PyTuple_GET_ITEM(subobj, i);
13188 if (!PyUnicode_Check(substring)) {
13189 PyErr_Format(PyExc_TypeError,
13190 "tuple for startswith must only contain str, "
13191 "not %.100s",
13192 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013193 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013194 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013195 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013196 if (result == -1)
13197 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013198 if (result) {
13199 Py_RETURN_TRUE;
13200 }
13201 }
13202 /* nothing matched */
13203 Py_RETURN_FALSE;
13204 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013205 if (!PyUnicode_Check(subobj)) {
13206 PyErr_Format(PyExc_TypeError,
13207 "startswith first arg must be str or "
13208 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013209 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013210 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013211 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013212 if (result == -1)
13213 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013214 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215}
13216
13217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013218PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013221Return True if S ends with the specified suffix, False otherwise.\n\
13222With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223With optional end, stop comparing S at that position.\n\
13224suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225
13226static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013227unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013229{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013230 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013231 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013232 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013233 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013234 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235
Jesus Ceaac451502011-04-20 17:09:23 +020013236 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013238 if (PyTuple_Check(subobj)) {
13239 Py_ssize_t i;
13240 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013241 substring = PyTuple_GET_ITEM(subobj, i);
13242 if (!PyUnicode_Check(substring)) {
13243 PyErr_Format(PyExc_TypeError,
13244 "tuple for endswith must only contain str, "
13245 "not %.100s",
13246 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013247 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013248 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013249 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013250 if (result == -1)
13251 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013252 if (result) {
13253 Py_RETURN_TRUE;
13254 }
13255 }
13256 Py_RETURN_FALSE;
13257 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013258 if (!PyUnicode_Check(subobj)) {
13259 PyErr_Format(PyExc_TypeError,
13260 "endswith first arg must be str or "
13261 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013263 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013264 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013265 if (result == -1)
13266 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013267 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268}
13269
Victor Stinner202fdca2012-05-07 12:47:02 +020013270Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013271_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013272{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013273 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13274 writer->data = PyUnicode_DATA(writer->buffer);
13275
13276 if (!writer->readonly) {
13277 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013278 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013279 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013280 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013281 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13282 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13283 writer->kind = PyUnicode_WCHAR_KIND;
13284 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13285
Victor Stinner8f674cc2013-04-17 23:02:17 +020013286 /* Copy-on-write mode: set buffer size to 0 so
13287 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13288 * next write. */
13289 writer->size = 0;
13290 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013291}
13292
Victor Stinnerd3f08822012-05-29 12:57:52 +020013293void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013294_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013295{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013296 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013297
13298 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013299 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013300
13301 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13302 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13303 writer->kind = PyUnicode_WCHAR_KIND;
13304 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013305}
13306
Victor Stinnerd3f08822012-05-29 12:57:52 +020013307int
13308_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13309 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013310{
13311 Py_ssize_t newlen;
13312 PyObject *newbuffer;
13313
Victor Stinner2740e462016-09-06 16:58:36 -070013314 assert(maxchar <= MAX_UNICODE);
13315
Victor Stinnerca9381e2015-09-22 00:58:32 +020013316 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013317 assert((maxchar > writer->maxchar && length >= 0)
13318 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013319
Victor Stinner202fdca2012-05-07 12:47:02 +020013320 if (length > PY_SSIZE_T_MAX - writer->pos) {
13321 PyErr_NoMemory();
13322 return -1;
13323 }
13324 newlen = writer->pos + length;
13325
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013326 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013327
Victor Stinnerd3f08822012-05-29 12:57:52 +020013328 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013329 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013330 if (writer->overallocate
13331 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13332 /* overallocate to limit the number of realloc() */
13333 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013334 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013335 if (newlen < writer->min_length)
13336 newlen = writer->min_length;
13337
Victor Stinnerd3f08822012-05-29 12:57:52 +020013338 writer->buffer = PyUnicode_New(newlen, maxchar);
13339 if (writer->buffer == NULL)
13340 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013341 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013342 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013343 if (writer->overallocate
13344 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13345 /* overallocate to limit the number of realloc() */
13346 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013347 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013348 if (newlen < writer->min_length)
13349 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013350
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013351 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013352 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013353 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013354 newbuffer = PyUnicode_New(newlen, maxchar);
13355 if (newbuffer == NULL)
13356 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013357 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13358 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013359 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013360 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013361 }
13362 else {
13363 newbuffer = resize_compact(writer->buffer, newlen);
13364 if (newbuffer == NULL)
13365 return -1;
13366 }
13367 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013368 }
13369 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013370 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013371 newbuffer = PyUnicode_New(writer->size, maxchar);
13372 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013373 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013374 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13375 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013376 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013377 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013378 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013379 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013380
13381#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013382}
13383
Victor Stinnerca9381e2015-09-22 00:58:32 +020013384int
13385_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13386 enum PyUnicode_Kind kind)
13387{
13388 Py_UCS4 maxchar;
13389
13390 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13391 assert(writer->kind < kind);
13392
13393 switch (kind)
13394 {
13395 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13396 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13397 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13398 default:
13399 assert(0 && "invalid kind");
13400 return -1;
13401 }
13402
13403 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13404}
13405
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013406Py_LOCAL_INLINE(int)
13407_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013408{
Victor Stinner2740e462016-09-06 16:58:36 -070013409 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013410 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13411 return -1;
13412 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13413 writer->pos++;
13414 return 0;
13415}
13416
13417int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013418_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13419{
13420 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13421}
13422
13423int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013424_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13425{
13426 Py_UCS4 maxchar;
13427 Py_ssize_t len;
13428
13429 if (PyUnicode_READY(str) == -1)
13430 return -1;
13431 len = PyUnicode_GET_LENGTH(str);
13432 if (len == 0)
13433 return 0;
13434 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13435 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013436 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013437 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013438 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013439 Py_INCREF(str);
13440 writer->buffer = str;
13441 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013442 writer->pos += len;
13443 return 0;
13444 }
13445 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13446 return -1;
13447 }
13448 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13449 str, 0, len);
13450 writer->pos += len;
13451 return 0;
13452}
13453
Victor Stinnere215d962012-10-06 23:03:36 +020013454int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013455_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13456 Py_ssize_t start, Py_ssize_t end)
13457{
13458 Py_UCS4 maxchar;
13459 Py_ssize_t len;
13460
13461 if (PyUnicode_READY(str) == -1)
13462 return -1;
13463
13464 assert(0 <= start);
13465 assert(end <= PyUnicode_GET_LENGTH(str));
13466 assert(start <= end);
13467
13468 if (end == 0)
13469 return 0;
13470
13471 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13472 return _PyUnicodeWriter_WriteStr(writer, str);
13473
13474 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13475 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13476 else
13477 maxchar = writer->maxchar;
13478 len = end - start;
13479
13480 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13481 return -1;
13482
13483 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13484 str, start, len);
13485 writer->pos += len;
13486 return 0;
13487}
13488
13489int
Victor Stinner4a587072013-11-19 12:54:53 +010013490_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13491 const char *ascii, Py_ssize_t len)
13492{
13493 if (len == -1)
13494 len = strlen(ascii);
13495
13496 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13497
13498 if (writer->buffer == NULL && !writer->overallocate) {
13499 PyObject *str;
13500
13501 str = _PyUnicode_FromASCII(ascii, len);
13502 if (str == NULL)
13503 return -1;
13504
13505 writer->readonly = 1;
13506 writer->buffer = str;
13507 _PyUnicodeWriter_Update(writer);
13508 writer->pos += len;
13509 return 0;
13510 }
13511
13512 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13513 return -1;
13514
13515 switch (writer->kind)
13516 {
13517 case PyUnicode_1BYTE_KIND:
13518 {
13519 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13520 Py_UCS1 *data = writer->data;
13521
13522 Py_MEMCPY(data + writer->pos, str, len);
13523 break;
13524 }
13525 case PyUnicode_2BYTE_KIND:
13526 {
13527 _PyUnicode_CONVERT_BYTES(
13528 Py_UCS1, Py_UCS2,
13529 ascii, ascii + len,
13530 (Py_UCS2 *)writer->data + writer->pos);
13531 break;
13532 }
13533 case PyUnicode_4BYTE_KIND:
13534 {
13535 _PyUnicode_CONVERT_BYTES(
13536 Py_UCS1, Py_UCS4,
13537 ascii, ascii + len,
13538 (Py_UCS4 *)writer->data + writer->pos);
13539 break;
13540 }
13541 default:
13542 assert(0);
13543 }
13544
13545 writer->pos += len;
13546 return 0;
13547}
13548
13549int
13550_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13551 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013552{
13553 Py_UCS4 maxchar;
13554
13555 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13556 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13557 return -1;
13558 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13559 writer->pos += len;
13560 return 0;
13561}
13562
Victor Stinnerd3f08822012-05-29 12:57:52 +020013563PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013564_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013565{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013566 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013567 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013568 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013569 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013570 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013571 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013572 str = writer->buffer;
13573 writer->buffer = NULL;
13574 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13575 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013576 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013577 if (writer->pos == 0) {
13578 Py_CLEAR(writer->buffer);
13579
13580 /* Get the empty Unicode string singleton ('') */
13581 _Py_INCREF_UNICODE_EMPTY();
13582 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013583 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013584 else {
13585 str = writer->buffer;
13586 writer->buffer = NULL;
13587
13588 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13589 PyObject *str2;
13590 str2 = resize_compact(str, writer->pos);
13591 if (str2 == NULL)
13592 return NULL;
13593 str = str2;
13594 }
13595 }
13596
Victor Stinner15a0bd32013-07-08 22:29:55 +020013597 assert(_PyUnicode_CheckConsistency(str, 1));
13598 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013599}
13600
Victor Stinnerd3f08822012-05-29 12:57:52 +020013601void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013602_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013603{
13604 Py_CLEAR(writer->buffer);
13605}
13606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013607#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013608
13609PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013611\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013612Return a formatted version of S, using substitutions from args and kwargs.\n\
13613The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013614
Eric Smith27bbca62010-11-04 17:06:58 +000013615PyDoc_STRVAR(format_map__doc__,
13616 "S.format_map(mapping) -> str\n\
13617\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013618Return a formatted version of S, using substitutions from mapping.\n\
13619The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013620
Eric Smith4a7d76d2008-05-30 18:10:19 +000013621static PyObject *
13622unicode__format__(PyObject* self, PyObject* args)
13623{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013624 PyObject *format_spec;
13625 _PyUnicodeWriter writer;
13626 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013627
13628 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13629 return NULL;
13630
Victor Stinnerd3f08822012-05-29 12:57:52 +020013631 if (PyUnicode_READY(self) == -1)
13632 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013633 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013634 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13635 self, format_spec, 0,
13636 PyUnicode_GET_LENGTH(format_spec));
13637 if (ret == -1) {
13638 _PyUnicodeWriter_Dealloc(&writer);
13639 return NULL;
13640 }
13641 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013642}
13643
Eric Smith8c663262007-08-25 02:26:07 +000013644PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013646\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013647Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013648
13649static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013650unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013651{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013652 Py_ssize_t size;
13653
13654 /* If it's a compact object, account for base structure +
13655 character data. */
13656 if (PyUnicode_IS_COMPACT_ASCII(v))
13657 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13658 else if (PyUnicode_IS_COMPACT(v))
13659 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013660 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013661 else {
13662 /* If it is a two-block object, account for base object, and
13663 for character block if present. */
13664 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013665 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013666 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013667 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013668 }
13669 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013670 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013671 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013672 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013673 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013674 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013675
13676 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013677}
13678
13679PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013680 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013681
13682static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013683unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013684{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013685 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013686 if (!copy)
13687 return NULL;
13688 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013689}
13690
Guido van Rossumd57fd912000-03-10 22:53:23 +000013691static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013692 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013693 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013694 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13695 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013696 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13697 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013698 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013699 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13700 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13701 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013702 {"expandtabs", (PyCFunction) unicode_expandtabs,
13703 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013704 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013705 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013706 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13707 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13708 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013709 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013710 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13711 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13712 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013713 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013714 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013715 {"splitlines", (PyCFunction) unicode_splitlines,
13716 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013717 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013718 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13719 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13720 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13721 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13722 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13723 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13724 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13725 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13726 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13727 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13728 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13729 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13730 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13731 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013732 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013733 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013734 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013735 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013736 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013737 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013738 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013739 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013740#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013741 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013742 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013743#endif
13744
Benjamin Peterson14339b62009-01-31 16:36:08 +000013745 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013746 {NULL, NULL}
13747};
13748
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013749static PyObject *
13750unicode_mod(PyObject *v, PyObject *w)
13751{
Brian Curtindfc80e32011-08-10 20:28:54 -050013752 if (!PyUnicode_Check(v))
13753 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013754 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013755}
13756
13757static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013758 0, /*nb_add*/
13759 0, /*nb_subtract*/
13760 0, /*nb_multiply*/
13761 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013762};
13763
Guido van Rossumd57fd912000-03-10 22:53:23 +000013764static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013765 (lenfunc) unicode_length, /* sq_length */
13766 PyUnicode_Concat, /* sq_concat */
13767 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13768 (ssizeargfunc) unicode_getitem, /* sq_item */
13769 0, /* sq_slice */
13770 0, /* sq_ass_item */
13771 0, /* sq_ass_slice */
13772 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013773};
13774
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013775static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013776unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013777{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013778 if (PyUnicode_READY(self) == -1)
13779 return NULL;
13780
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013781 if (PyIndex_Check(item)) {
13782 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013783 if (i == -1 && PyErr_Occurred())
13784 return NULL;
13785 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013786 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013787 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013788 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013789 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013790 PyObject *result;
13791 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013792 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013793 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013794
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013795 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013796 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013797 return NULL;
13798 }
13799
13800 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013801 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013802 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013803 slicelength == PyUnicode_GET_LENGTH(self)) {
13804 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013805 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013806 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013807 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013808 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013809 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013810 src_kind = PyUnicode_KIND(self);
13811 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013812 if (!PyUnicode_IS_ASCII(self)) {
13813 kind_limit = kind_maxchar_limit(src_kind);
13814 max_char = 0;
13815 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13816 ch = PyUnicode_READ(src_kind, src_data, cur);
13817 if (ch > max_char) {
13818 max_char = ch;
13819 if (max_char >= kind_limit)
13820 break;
13821 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013822 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013823 }
Victor Stinner55c99112011-10-13 01:17:06 +020013824 else
13825 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013826 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013827 if (result == NULL)
13828 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013829 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013830 dest_data = PyUnicode_DATA(result);
13831
13832 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013833 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13834 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013835 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013836 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013837 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013838 } else {
13839 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13840 return NULL;
13841 }
13842}
13843
13844static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013845 (lenfunc)unicode_length, /* mp_length */
13846 (binaryfunc)unicode_subscript, /* mp_subscript */
13847 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013848};
13849
Guido van Rossumd57fd912000-03-10 22:53:23 +000013850
Guido van Rossumd57fd912000-03-10 22:53:23 +000013851/* Helpers for PyUnicode_Format() */
13852
Victor Stinnera47082312012-10-04 02:19:54 +020013853struct unicode_formatter_t {
13854 PyObject *args;
13855 int args_owned;
13856 Py_ssize_t arglen, argidx;
13857 PyObject *dict;
13858
13859 enum PyUnicode_Kind fmtkind;
13860 Py_ssize_t fmtcnt, fmtpos;
13861 void *fmtdata;
13862 PyObject *fmtstr;
13863
13864 _PyUnicodeWriter writer;
13865};
13866
13867struct unicode_format_arg_t {
13868 Py_UCS4 ch;
13869 int flags;
13870 Py_ssize_t width;
13871 int prec;
13872 int sign;
13873};
13874
Guido van Rossumd57fd912000-03-10 22:53:23 +000013875static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013876unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013877{
Victor Stinnera47082312012-10-04 02:19:54 +020013878 Py_ssize_t argidx = ctx->argidx;
13879
13880 if (argidx < ctx->arglen) {
13881 ctx->argidx++;
13882 if (ctx->arglen < 0)
13883 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013884 else
Victor Stinnera47082312012-10-04 02:19:54 +020013885 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886 }
13887 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013888 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013889 return NULL;
13890}
13891
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013892/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013893
Victor Stinnera47082312012-10-04 02:19:54 +020013894/* Format a float into the writer if the writer is not NULL, or into *p_output
13895 otherwise.
13896
13897 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013898static int
Victor Stinnera47082312012-10-04 02:19:54 +020013899formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13900 PyObject **p_output,
13901 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013902{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013903 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013905 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013906 int prec;
13907 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013908
Guido van Rossumd57fd912000-03-10 22:53:23 +000013909 x = PyFloat_AsDouble(v);
13910 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013911 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013912
Victor Stinnera47082312012-10-04 02:19:54 +020013913 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013914 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013915 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013916
Victor Stinnera47082312012-10-04 02:19:54 +020013917 if (arg->flags & F_ALT)
13918 dtoa_flags = Py_DTSF_ALT;
13919 else
13920 dtoa_flags = 0;
13921 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013922 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013923 return -1;
13924 len = strlen(p);
13925 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013926 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013927 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013928 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013929 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013930 }
13931 else
13932 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013933 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013934 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013935}
13936
Victor Stinnerd0880d52012-04-27 23:40:13 +020013937/* formatlong() emulates the format codes d, u, o, x and X, and
13938 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13939 * Python's regular ints.
13940 * Return value: a new PyUnicodeObject*, or NULL if error.
13941 * The output string is of the form
13942 * "-"? ("0x" | "0X")? digit+
13943 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13944 * set in flags. The case of hex digits will be correct,
13945 * There will be at least prec digits, zero-filled on the left if
13946 * necessary to get that many.
13947 * val object to be converted
13948 * flags bitmask of format flags; only F_ALT is looked at
13949 * prec minimum number of digits; 0-fill on left if needed
13950 * type a character in [duoxX]; u acts the same as d
13951 *
13952 * CAUTION: o, x and X conversions on regular ints can never
13953 * produce a '-' sign, but can for Python's unbounded ints.
13954 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013955PyObject *
13956_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013957{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013958 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013959 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013960 Py_ssize_t i;
13961 int sign; /* 1 if '-', else 0 */
13962 int len; /* number of characters */
13963 Py_ssize_t llen;
13964 int numdigits; /* len == numnondigits + numdigits */
13965 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013966
Victor Stinnerd0880d52012-04-27 23:40:13 +020013967 /* Avoid exceeding SSIZE_T_MAX */
13968 if (prec > INT_MAX-3) {
13969 PyErr_SetString(PyExc_OverflowError,
13970 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013971 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013972 }
13973
13974 assert(PyLong_Check(val));
13975
13976 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013977 default:
13978 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013979 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013980 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013981 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013982 /* int and int subclasses should print numerically when a numeric */
13983 /* format code is used (see issue18780) */
13984 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013985 break;
13986 case 'o':
13987 numnondigits = 2;
13988 result = PyNumber_ToBase(val, 8);
13989 break;
13990 case 'x':
13991 case 'X':
13992 numnondigits = 2;
13993 result = PyNumber_ToBase(val, 16);
13994 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013995 }
13996 if (!result)
13997 return NULL;
13998
13999 assert(unicode_modifiable(result));
14000 assert(PyUnicode_IS_READY(result));
14001 assert(PyUnicode_IS_ASCII(result));
14002
14003 /* To modify the string in-place, there can only be one reference. */
14004 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014005 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014006 PyErr_BadInternalCall();
14007 return NULL;
14008 }
14009 buf = PyUnicode_DATA(result);
14010 llen = PyUnicode_GET_LENGTH(result);
14011 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014012 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014013 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014014 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014015 return NULL;
14016 }
14017 len = (int)llen;
14018 sign = buf[0] == '-';
14019 numnondigits += sign;
14020 numdigits = len - numnondigits;
14021 assert(numdigits > 0);
14022
14023 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014024 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014025 (type == 'o' || type == 'x' || type == 'X'))) {
14026 assert(buf[sign] == '0');
14027 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14028 buf[sign+1] == 'o');
14029 numnondigits -= 2;
14030 buf += 2;
14031 len -= 2;
14032 if (sign)
14033 buf[0] = '-';
14034 assert(len == numnondigits + numdigits);
14035 assert(numdigits > 0);
14036 }
14037
14038 /* Fill with leading zeroes to meet minimum width. */
14039 if (prec > numdigits) {
14040 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14041 numnondigits + prec);
14042 char *b1;
14043 if (!r1) {
14044 Py_DECREF(result);
14045 return NULL;
14046 }
14047 b1 = PyBytes_AS_STRING(r1);
14048 for (i = 0; i < numnondigits; ++i)
14049 *b1++ = *buf++;
14050 for (i = 0; i < prec - numdigits; i++)
14051 *b1++ = '0';
14052 for (i = 0; i < numdigits; i++)
14053 *b1++ = *buf++;
14054 *b1 = '\0';
14055 Py_DECREF(result);
14056 result = r1;
14057 buf = PyBytes_AS_STRING(result);
14058 len = numnondigits + prec;
14059 }
14060
14061 /* Fix up case for hex conversions. */
14062 if (type == 'X') {
14063 /* Need to convert all lower case letters to upper case.
14064 and need to convert 0x to 0X (and -0x to -0X). */
14065 for (i = 0; i < len; i++)
14066 if (buf[i] >= 'a' && buf[i] <= 'x')
14067 buf[i] -= 'a'-'A';
14068 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014069 if (!PyUnicode_Check(result)
14070 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014071 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014072 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014073 Py_DECREF(result);
14074 result = unicode;
14075 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014076 else if (len != PyUnicode_GET_LENGTH(result)) {
14077 if (PyUnicode_Resize(&result, len) < 0)
14078 Py_CLEAR(result);
14079 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014080 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014081}
14082
Ethan Furmandf3ed242014-01-05 06:50:30 -080014083/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014084 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014085 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014086 * -1 and raise an exception on error */
14087static int
Victor Stinnera47082312012-10-04 02:19:54 +020014088mainformatlong(PyObject *v,
14089 struct unicode_format_arg_t *arg,
14090 PyObject **p_output,
14091 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014092{
14093 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014094 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095
14096 if (!PyNumber_Check(v))
14097 goto wrongtype;
14098
Ethan Furman9ab74802014-03-21 06:38:46 -070014099 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014100 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014101 if (type == 'o' || type == 'x' || type == 'X') {
14102 iobj = PyNumber_Index(v);
14103 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014104 if (PyErr_ExceptionMatches(PyExc_TypeError))
14105 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014106 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014107 }
14108 }
14109 else {
14110 iobj = PyNumber_Long(v);
14111 if (iobj == NULL ) {
14112 if (PyErr_ExceptionMatches(PyExc_TypeError))
14113 goto wrongtype;
14114 return -1;
14115 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014116 }
14117 assert(PyLong_Check(iobj));
14118 }
14119 else {
14120 iobj = v;
14121 Py_INCREF(iobj);
14122 }
14123
14124 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014125 && arg->width == -1 && arg->prec == -1
14126 && !(arg->flags & (F_SIGN | F_BLANK))
14127 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014128 {
14129 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014130 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014131 int base;
14132
Victor Stinnera47082312012-10-04 02:19:54 +020014133 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014134 {
14135 default:
14136 assert(0 && "'type' not in [diuoxX]");
14137 case 'd':
14138 case 'i':
14139 case 'u':
14140 base = 10;
14141 break;
14142 case 'o':
14143 base = 8;
14144 break;
14145 case 'x':
14146 case 'X':
14147 base = 16;
14148 break;
14149 }
14150
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014151 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14152 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014153 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014154 }
14155 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014156 return 1;
14157 }
14158
Ethan Furmanb95b5612015-01-23 20:05:18 -080014159 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014160 Py_DECREF(iobj);
14161 if (res == NULL)
14162 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014163 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014164 return 0;
14165
14166wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014167 switch(type)
14168 {
14169 case 'o':
14170 case 'x':
14171 case 'X':
14172 PyErr_Format(PyExc_TypeError,
14173 "%%%c format: an integer is required, "
14174 "not %.200s",
14175 type, Py_TYPE(v)->tp_name);
14176 break;
14177 default:
14178 PyErr_Format(PyExc_TypeError,
14179 "%%%c format: a number is required, "
14180 "not %.200s",
14181 type, Py_TYPE(v)->tp_name);
14182 break;
14183 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014184 return -1;
14185}
14186
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014187static Py_UCS4
14188formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014189{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014190 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014191 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014192 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014193 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014194 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014195 goto onError;
14196 }
14197 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014198 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014199 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014200 /* make sure number is a type of integer */
14201 if (!PyLong_Check(v)) {
14202 iobj = PyNumber_Index(v);
14203 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014204 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014205 }
14206 v = iobj;
14207 Py_DECREF(iobj);
14208 }
14209 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014210 x = PyLong_AsLong(v);
14211 if (x == -1 && PyErr_Occurred())
14212 goto onError;
14213
Victor Stinner8faf8212011-12-08 22:14:11 +010014214 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014215 PyErr_SetString(PyExc_OverflowError,
14216 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014217 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014218 }
14219
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014220 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014221 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014222
Benjamin Peterson29060642009-01-31 22:14:21 +000014223 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014224 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014225 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014226 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014227}
14228
Victor Stinnera47082312012-10-04 02:19:54 +020014229/* Parse options of an argument: flags, width, precision.
14230 Handle also "%(name)" syntax.
14231
14232 Return 0 if the argument has been formatted into arg->str.
14233 Return 1 if the argument has been written into ctx->writer,
14234 Raise an exception and return -1 on error. */
14235static int
14236unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14237 struct unicode_format_arg_t *arg)
14238{
14239#define FORMAT_READ(ctx) \
14240 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14241
14242 PyObject *v;
14243
Victor Stinnera47082312012-10-04 02:19:54 +020014244 if (arg->ch == '(') {
14245 /* Get argument value from a dictionary. Example: "%(name)s". */
14246 Py_ssize_t keystart;
14247 Py_ssize_t keylen;
14248 PyObject *key;
14249 int pcount = 1;
14250
14251 if (ctx->dict == NULL) {
14252 PyErr_SetString(PyExc_TypeError,
14253 "format requires a mapping");
14254 return -1;
14255 }
14256 ++ctx->fmtpos;
14257 --ctx->fmtcnt;
14258 keystart = ctx->fmtpos;
14259 /* Skip over balanced parentheses */
14260 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14261 arg->ch = FORMAT_READ(ctx);
14262 if (arg->ch == ')')
14263 --pcount;
14264 else if (arg->ch == '(')
14265 ++pcount;
14266 ctx->fmtpos++;
14267 }
14268 keylen = ctx->fmtpos - keystart - 1;
14269 if (ctx->fmtcnt < 0 || pcount > 0) {
14270 PyErr_SetString(PyExc_ValueError,
14271 "incomplete format key");
14272 return -1;
14273 }
14274 key = PyUnicode_Substring(ctx->fmtstr,
14275 keystart, keystart + keylen);
14276 if (key == NULL)
14277 return -1;
14278 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014279 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014280 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014281 }
14282 ctx->args = PyObject_GetItem(ctx->dict, key);
14283 Py_DECREF(key);
14284 if (ctx->args == NULL)
14285 return -1;
14286 ctx->args_owned = 1;
14287 ctx->arglen = -1;
14288 ctx->argidx = -2;
14289 }
14290
14291 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014292 while (--ctx->fmtcnt >= 0) {
14293 arg->ch = FORMAT_READ(ctx);
14294 ctx->fmtpos++;
14295 switch (arg->ch) {
14296 case '-': arg->flags |= F_LJUST; continue;
14297 case '+': arg->flags |= F_SIGN; continue;
14298 case ' ': arg->flags |= F_BLANK; continue;
14299 case '#': arg->flags |= F_ALT; continue;
14300 case '0': arg->flags |= F_ZERO; continue;
14301 }
14302 break;
14303 }
14304
14305 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014306 if (arg->ch == '*') {
14307 v = unicode_format_getnextarg(ctx);
14308 if (v == NULL)
14309 return -1;
14310 if (!PyLong_Check(v)) {
14311 PyErr_SetString(PyExc_TypeError,
14312 "* wants int");
14313 return -1;
14314 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014315 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014316 if (arg->width == -1 && PyErr_Occurred())
14317 return -1;
14318 if (arg->width < 0) {
14319 arg->flags |= F_LJUST;
14320 arg->width = -arg->width;
14321 }
14322 if (--ctx->fmtcnt >= 0) {
14323 arg->ch = FORMAT_READ(ctx);
14324 ctx->fmtpos++;
14325 }
14326 }
14327 else if (arg->ch >= '0' && arg->ch <= '9') {
14328 arg->width = arg->ch - '0';
14329 while (--ctx->fmtcnt >= 0) {
14330 arg->ch = FORMAT_READ(ctx);
14331 ctx->fmtpos++;
14332 if (arg->ch < '0' || arg->ch > '9')
14333 break;
14334 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14335 mixing signed and unsigned comparison. Since arg->ch is between
14336 '0' and '9', casting to int is safe. */
14337 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14338 PyErr_SetString(PyExc_ValueError,
14339 "width too big");
14340 return -1;
14341 }
14342 arg->width = arg->width*10 + (arg->ch - '0');
14343 }
14344 }
14345
14346 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014347 if (arg->ch == '.') {
14348 arg->prec = 0;
14349 if (--ctx->fmtcnt >= 0) {
14350 arg->ch = FORMAT_READ(ctx);
14351 ctx->fmtpos++;
14352 }
14353 if (arg->ch == '*') {
14354 v = unicode_format_getnextarg(ctx);
14355 if (v == NULL)
14356 return -1;
14357 if (!PyLong_Check(v)) {
14358 PyErr_SetString(PyExc_TypeError,
14359 "* wants int");
14360 return -1;
14361 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014362 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014363 if (arg->prec == -1 && PyErr_Occurred())
14364 return -1;
14365 if (arg->prec < 0)
14366 arg->prec = 0;
14367 if (--ctx->fmtcnt >= 0) {
14368 arg->ch = FORMAT_READ(ctx);
14369 ctx->fmtpos++;
14370 }
14371 }
14372 else if (arg->ch >= '0' && arg->ch <= '9') {
14373 arg->prec = arg->ch - '0';
14374 while (--ctx->fmtcnt >= 0) {
14375 arg->ch = FORMAT_READ(ctx);
14376 ctx->fmtpos++;
14377 if (arg->ch < '0' || arg->ch > '9')
14378 break;
14379 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14380 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014381 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014382 return -1;
14383 }
14384 arg->prec = arg->prec*10 + (arg->ch - '0');
14385 }
14386 }
14387 }
14388
14389 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14390 if (ctx->fmtcnt >= 0) {
14391 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14392 if (--ctx->fmtcnt >= 0) {
14393 arg->ch = FORMAT_READ(ctx);
14394 ctx->fmtpos++;
14395 }
14396 }
14397 }
14398 if (ctx->fmtcnt < 0) {
14399 PyErr_SetString(PyExc_ValueError,
14400 "incomplete format");
14401 return -1;
14402 }
14403 return 0;
14404
14405#undef FORMAT_READ
14406}
14407
14408/* Format one argument. Supported conversion specifiers:
14409
14410 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014411 - "i", "d", "u": int or float
14412 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014413 - "e", "E", "f", "F", "g", "G": float
14414 - "c": int or str (1 character)
14415
Victor Stinner8dbd4212012-12-04 09:30:24 +010014416 When possible, the output is written directly into the Unicode writer
14417 (ctx->writer). A string is created when padding is required.
14418
Victor Stinnera47082312012-10-04 02:19:54 +020014419 Return 0 if the argument has been formatted into *p_str,
14420 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014421 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014422static int
14423unicode_format_arg_format(struct unicode_formatter_t *ctx,
14424 struct unicode_format_arg_t *arg,
14425 PyObject **p_str)
14426{
14427 PyObject *v;
14428 _PyUnicodeWriter *writer = &ctx->writer;
14429
14430 if (ctx->fmtcnt == 0)
14431 ctx->writer.overallocate = 0;
14432
14433 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014434 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014435 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014436 return 1;
14437 }
14438
14439 v = unicode_format_getnextarg(ctx);
14440 if (v == NULL)
14441 return -1;
14442
Victor Stinnera47082312012-10-04 02:19:54 +020014443
14444 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014445 case 's':
14446 case 'r':
14447 case 'a':
14448 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14449 /* Fast path */
14450 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14451 return -1;
14452 return 1;
14453 }
14454
14455 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14456 *p_str = v;
14457 Py_INCREF(*p_str);
14458 }
14459 else {
14460 if (arg->ch == 's')
14461 *p_str = PyObject_Str(v);
14462 else if (arg->ch == 'r')
14463 *p_str = PyObject_Repr(v);
14464 else
14465 *p_str = PyObject_ASCII(v);
14466 }
14467 break;
14468
14469 case 'i':
14470 case 'd':
14471 case 'u':
14472 case 'o':
14473 case 'x':
14474 case 'X':
14475 {
14476 int ret = mainformatlong(v, arg, p_str, writer);
14477 if (ret != 0)
14478 return ret;
14479 arg->sign = 1;
14480 break;
14481 }
14482
14483 case 'e':
14484 case 'E':
14485 case 'f':
14486 case 'F':
14487 case 'g':
14488 case 'G':
14489 if (arg->width == -1 && arg->prec == -1
14490 && !(arg->flags & (F_SIGN | F_BLANK)))
14491 {
14492 /* Fast path */
14493 if (formatfloat(v, arg, NULL, writer) == -1)
14494 return -1;
14495 return 1;
14496 }
14497
14498 arg->sign = 1;
14499 if (formatfloat(v, arg, p_str, NULL) == -1)
14500 return -1;
14501 break;
14502
14503 case 'c':
14504 {
14505 Py_UCS4 ch = formatchar(v);
14506 if (ch == (Py_UCS4) -1)
14507 return -1;
14508 if (arg->width == -1 && arg->prec == -1) {
14509 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014510 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014511 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014512 return 1;
14513 }
14514 *p_str = PyUnicode_FromOrdinal(ch);
14515 break;
14516 }
14517
14518 default:
14519 PyErr_Format(PyExc_ValueError,
14520 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014521 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014522 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14523 (int)arg->ch,
14524 ctx->fmtpos - 1);
14525 return -1;
14526 }
14527 if (*p_str == NULL)
14528 return -1;
14529 assert (PyUnicode_Check(*p_str));
14530 return 0;
14531}
14532
14533static int
14534unicode_format_arg_output(struct unicode_formatter_t *ctx,
14535 struct unicode_format_arg_t *arg,
14536 PyObject *str)
14537{
14538 Py_ssize_t len;
14539 enum PyUnicode_Kind kind;
14540 void *pbuf;
14541 Py_ssize_t pindex;
14542 Py_UCS4 signchar;
14543 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014544 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014545 Py_ssize_t sublen;
14546 _PyUnicodeWriter *writer = &ctx->writer;
14547 Py_UCS4 fill;
14548
14549 fill = ' ';
14550 if (arg->sign && arg->flags & F_ZERO)
14551 fill = '0';
14552
14553 if (PyUnicode_READY(str) == -1)
14554 return -1;
14555
14556 len = PyUnicode_GET_LENGTH(str);
14557 if ((arg->width == -1 || arg->width <= len)
14558 && (arg->prec == -1 || arg->prec >= len)
14559 && !(arg->flags & (F_SIGN | F_BLANK)))
14560 {
14561 /* Fast path */
14562 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14563 return -1;
14564 return 0;
14565 }
14566
14567 /* Truncate the string for "s", "r" and "a" formats
14568 if the precision is set */
14569 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14570 if (arg->prec >= 0 && len > arg->prec)
14571 len = arg->prec;
14572 }
14573
14574 /* Adjust sign and width */
14575 kind = PyUnicode_KIND(str);
14576 pbuf = PyUnicode_DATA(str);
14577 pindex = 0;
14578 signchar = '\0';
14579 if (arg->sign) {
14580 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14581 if (ch == '-' || ch == '+') {
14582 signchar = ch;
14583 len--;
14584 pindex++;
14585 }
14586 else if (arg->flags & F_SIGN)
14587 signchar = '+';
14588 else if (arg->flags & F_BLANK)
14589 signchar = ' ';
14590 else
14591 arg->sign = 0;
14592 }
14593 if (arg->width < len)
14594 arg->width = len;
14595
14596 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014597 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014598 if (!(arg->flags & F_LJUST)) {
14599 if (arg->sign) {
14600 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014601 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014602 }
14603 else {
14604 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014605 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014606 }
14607 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014608 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14609 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014610 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014611 }
14612
Victor Stinnera47082312012-10-04 02:19:54 +020014613 buflen = arg->width;
14614 if (arg->sign && len == arg->width)
14615 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014616 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014617 return -1;
14618
14619 /* Write the sign if needed */
14620 if (arg->sign) {
14621 if (fill != ' ') {
14622 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14623 writer->pos += 1;
14624 }
14625 if (arg->width > len)
14626 arg->width--;
14627 }
14628
14629 /* Write the numeric prefix for "x", "X" and "o" formats
14630 if the alternate form is used.
14631 For example, write "0x" for the "%#x" format. */
14632 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14633 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14634 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14635 if (fill != ' ') {
14636 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14637 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14638 writer->pos += 2;
14639 pindex += 2;
14640 }
14641 arg->width -= 2;
14642 if (arg->width < 0)
14643 arg->width = 0;
14644 len -= 2;
14645 }
14646
14647 /* Pad left with the fill character if needed */
14648 if (arg->width > len && !(arg->flags & F_LJUST)) {
14649 sublen = arg->width - len;
14650 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14651 writer->pos += sublen;
14652 arg->width = len;
14653 }
14654
14655 /* If padding with spaces: write sign if needed and/or numeric prefix if
14656 the alternate form is used */
14657 if (fill == ' ') {
14658 if (arg->sign) {
14659 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14660 writer->pos += 1;
14661 }
14662 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14663 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14664 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14665 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14666 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14667 writer->pos += 2;
14668 pindex += 2;
14669 }
14670 }
14671
14672 /* Write characters */
14673 if (len) {
14674 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14675 str, pindex, len);
14676 writer->pos += len;
14677 }
14678
14679 /* Pad right with the fill character if needed */
14680 if (arg->width > len) {
14681 sublen = arg->width - len;
14682 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14683 writer->pos += sublen;
14684 }
14685 return 0;
14686}
14687
14688/* Helper of PyUnicode_Format(): format one arg.
14689 Return 0 on success, raise an exception and return -1 on error. */
14690static int
14691unicode_format_arg(struct unicode_formatter_t *ctx)
14692{
14693 struct unicode_format_arg_t arg;
14694 PyObject *str;
14695 int ret;
14696
Victor Stinner8dbd4212012-12-04 09:30:24 +010014697 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14698 arg.flags = 0;
14699 arg.width = -1;
14700 arg.prec = -1;
14701 arg.sign = 0;
14702 str = NULL;
14703
Victor Stinnera47082312012-10-04 02:19:54 +020014704 ret = unicode_format_arg_parse(ctx, &arg);
14705 if (ret == -1)
14706 return -1;
14707
14708 ret = unicode_format_arg_format(ctx, &arg, &str);
14709 if (ret == -1)
14710 return -1;
14711
14712 if (ret != 1) {
14713 ret = unicode_format_arg_output(ctx, &arg, str);
14714 Py_DECREF(str);
14715 if (ret == -1)
14716 return -1;
14717 }
14718
14719 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14720 PyErr_SetString(PyExc_TypeError,
14721 "not all arguments converted during string formatting");
14722 return -1;
14723 }
14724 return 0;
14725}
14726
Alexander Belopolsky40018472011-02-26 01:02:56 +000014727PyObject *
14728PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014729{
Victor Stinnera47082312012-10-04 02:19:54 +020014730 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014731
Guido van Rossumd57fd912000-03-10 22:53:23 +000014732 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014733 PyErr_BadInternalCall();
14734 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014735 }
Victor Stinnera47082312012-10-04 02:19:54 +020014736
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014737 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014738 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014739
14740 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014741 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14742 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14743 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14744 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014745
Victor Stinner8f674cc2013-04-17 23:02:17 +020014746 _PyUnicodeWriter_Init(&ctx.writer);
14747 ctx.writer.min_length = ctx.fmtcnt + 100;
14748 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014749
Guido van Rossumd57fd912000-03-10 22:53:23 +000014750 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014751 ctx.arglen = PyTuple_Size(args);
14752 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014753 }
14754 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014755 ctx.arglen = -1;
14756 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014757 }
Victor Stinnera47082312012-10-04 02:19:54 +020014758 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014759 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014760 ctx.dict = args;
14761 else
14762 ctx.dict = NULL;
14763 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014764
Victor Stinnera47082312012-10-04 02:19:54 +020014765 while (--ctx.fmtcnt >= 0) {
14766 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014767 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014768
14769 nonfmtpos = ctx.fmtpos++;
14770 while (ctx.fmtcnt >= 0 &&
14771 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14772 ctx.fmtpos++;
14773 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014774 }
Victor Stinnera47082312012-10-04 02:19:54 +020014775 if (ctx.fmtcnt < 0) {
14776 ctx.fmtpos--;
14777 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014778 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014779
Victor Stinnercfc4c132013-04-03 01:48:39 +020014780 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14781 nonfmtpos, ctx.fmtpos) < 0)
14782 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014783 }
14784 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014785 ctx.fmtpos++;
14786 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014787 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014788 }
14789 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014790
Victor Stinnera47082312012-10-04 02:19:54 +020014791 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014792 PyErr_SetString(PyExc_TypeError,
14793 "not all arguments converted during string formatting");
14794 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014795 }
14796
Victor Stinnera47082312012-10-04 02:19:54 +020014797 if (ctx.args_owned) {
14798 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014799 }
Victor Stinnera47082312012-10-04 02:19:54 +020014800 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014801
Benjamin Peterson29060642009-01-31 22:14:21 +000014802 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014803 _PyUnicodeWriter_Dealloc(&ctx.writer);
14804 if (ctx.args_owned) {
14805 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014806 }
14807 return NULL;
14808}
14809
Jeremy Hylton938ace62002-07-17 16:30:39 +000014810static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014811unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14812
Tim Peters6d6c1a32001-08-02 04:15:00 +000014813static PyObject *
14814unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14815{
Benjamin Peterson29060642009-01-31 22:14:21 +000014816 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014817 static char *kwlist[] = {"object", "encoding", "errors", 0};
14818 char *encoding = NULL;
14819 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014820
Benjamin Peterson14339b62009-01-31 16:36:08 +000014821 if (type != &PyUnicode_Type)
14822 return unicode_subtype_new(type, args, kwds);
14823 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014824 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014825 return NULL;
14826 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014827 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014828 if (encoding == NULL && errors == NULL)
14829 return PyObject_Str(x);
14830 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014831 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014832}
14833
Guido van Rossume023fe02001-08-30 03:12:59 +000014834static PyObject *
14835unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14836{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014837 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014838 Py_ssize_t length, char_size;
14839 int share_wstr, share_utf8;
14840 unsigned int kind;
14841 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014842
Benjamin Peterson14339b62009-01-31 16:36:08 +000014843 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014844
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014845 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014846 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014847 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014848 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014849 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014850 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014851 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014852 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014853
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014854 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014855 if (self == NULL) {
14856 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014857 return NULL;
14858 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014859 kind = PyUnicode_KIND(unicode);
14860 length = PyUnicode_GET_LENGTH(unicode);
14861
14862 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014863#ifdef Py_DEBUG
14864 _PyUnicode_HASH(self) = -1;
14865#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014866 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014867#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014868 _PyUnicode_STATE(self).interned = 0;
14869 _PyUnicode_STATE(self).kind = kind;
14870 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014871 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014872 _PyUnicode_STATE(self).ready = 1;
14873 _PyUnicode_WSTR(self) = NULL;
14874 _PyUnicode_UTF8_LENGTH(self) = 0;
14875 _PyUnicode_UTF8(self) = NULL;
14876 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014877 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014878
14879 share_utf8 = 0;
14880 share_wstr = 0;
14881 if (kind == PyUnicode_1BYTE_KIND) {
14882 char_size = 1;
14883 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14884 share_utf8 = 1;
14885 }
14886 else if (kind == PyUnicode_2BYTE_KIND) {
14887 char_size = 2;
14888 if (sizeof(wchar_t) == 2)
14889 share_wstr = 1;
14890 }
14891 else {
14892 assert(kind == PyUnicode_4BYTE_KIND);
14893 char_size = 4;
14894 if (sizeof(wchar_t) == 4)
14895 share_wstr = 1;
14896 }
14897
14898 /* Ensure we won't overflow the length. */
14899 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14900 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014901 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014902 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014903 data = PyObject_MALLOC((length + 1) * char_size);
14904 if (data == NULL) {
14905 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014906 goto onError;
14907 }
14908
Victor Stinnerc3c74152011-10-02 20:39:55 +020014909 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014910 if (share_utf8) {
14911 _PyUnicode_UTF8_LENGTH(self) = length;
14912 _PyUnicode_UTF8(self) = data;
14913 }
14914 if (share_wstr) {
14915 _PyUnicode_WSTR_LENGTH(self) = length;
14916 _PyUnicode_WSTR(self) = (wchar_t *)data;
14917 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014918
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014919 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014920 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014921 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014922#ifdef Py_DEBUG
14923 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14924#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014925 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014926 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014927
14928onError:
14929 Py_DECREF(unicode);
14930 Py_DECREF(self);
14931 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014932}
14933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014934PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014935"str(object='') -> str\n\
14936str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014937\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014938Create a new string object from the given object. If encoding or\n\
14939errors is specified, then the object must expose a data buffer\n\
14940that will be decoded using the given encoding and error handler.\n\
14941Otherwise, returns the result of object.__str__() (if defined)\n\
14942or repr(object).\n\
14943encoding defaults to sys.getdefaultencoding().\n\
14944errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014945
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014946static PyObject *unicode_iter(PyObject *seq);
14947
Guido van Rossumd57fd912000-03-10 22:53:23 +000014948PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014949 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014950 "str", /* tp_name */
14951 sizeof(PyUnicodeObject), /* tp_size */
14952 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014953 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014954 (destructor)unicode_dealloc, /* tp_dealloc */
14955 0, /* tp_print */
14956 0, /* tp_getattr */
14957 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014958 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014959 unicode_repr, /* tp_repr */
14960 &unicode_as_number, /* tp_as_number */
14961 &unicode_as_sequence, /* tp_as_sequence */
14962 &unicode_as_mapping, /* tp_as_mapping */
14963 (hashfunc) unicode_hash, /* tp_hash*/
14964 0, /* tp_call*/
14965 (reprfunc) unicode_str, /* tp_str */
14966 PyObject_GenericGetAttr, /* tp_getattro */
14967 0, /* tp_setattro */
14968 0, /* tp_as_buffer */
14969 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014970 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014971 unicode_doc, /* tp_doc */
14972 0, /* tp_traverse */
14973 0, /* tp_clear */
14974 PyUnicode_RichCompare, /* tp_richcompare */
14975 0, /* tp_weaklistoffset */
14976 unicode_iter, /* tp_iter */
14977 0, /* tp_iternext */
14978 unicode_methods, /* tp_methods */
14979 0, /* tp_members */
14980 0, /* tp_getset */
14981 &PyBaseObject_Type, /* tp_base */
14982 0, /* tp_dict */
14983 0, /* tp_descr_get */
14984 0, /* tp_descr_set */
14985 0, /* tp_dictoffset */
14986 0, /* tp_init */
14987 0, /* tp_alloc */
14988 unicode_new, /* tp_new */
14989 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014990};
14991
14992/* Initialize the Unicode implementation */
14993
Victor Stinner3a50e702011-10-18 21:21:00 +020014994int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014995{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014996 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014997 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014998 0x000A, /* LINE FEED */
14999 0x000D, /* CARRIAGE RETURN */
15000 0x001C, /* FILE SEPARATOR */
15001 0x001D, /* GROUP SEPARATOR */
15002 0x001E, /* RECORD SEPARATOR */
15003 0x0085, /* NEXT LINE */
15004 0x2028, /* LINE SEPARATOR */
15005 0x2029, /* PARAGRAPH SEPARATOR */
15006 };
15007
Fred Drakee4315f52000-05-09 19:53:39 +000015008 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015009 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015010 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015011 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015012 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015013
Guido van Rossumcacfc072002-05-24 19:01:59 +000015014 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015015 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015016
15017 /* initialize the linebreak bloom filter */
15018 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015019 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015020 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015021
Christian Heimes26532f72013-07-20 14:57:16 +020015022 if (PyType_Ready(&EncodingMapType) < 0)
15023 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015024
Benjamin Petersonc4311282012-10-30 23:21:10 -040015025 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15026 Py_FatalError("Can't initialize field name iterator type");
15027
15028 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15029 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015030
Victor Stinner3a50e702011-10-18 21:21:00 +020015031 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015032}
15033
15034/* Finalize the Unicode implementation */
15035
Christian Heimesa156e092008-02-16 07:38:31 +000015036int
15037PyUnicode_ClearFreeList(void)
15038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015039 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015040}
15041
Guido van Rossumd57fd912000-03-10 22:53:23 +000015042void
Thomas Wouters78890102000-07-22 19:25:51 +000015043_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015044{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015045 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015046
Serhiy Storchaka05997252013-01-26 12:14:02 +020015047 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015048
Serhiy Storchaka05997252013-01-26 12:14:02 +020015049 for (i = 0; i < 256; i++)
15050 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015051 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015052 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015053}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015054
Walter Dörwald16807132007-05-25 13:52:07 +000015055void
15056PyUnicode_InternInPlace(PyObject **p)
15057{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015058 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015059 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015060#ifdef Py_DEBUG
15061 assert(s != NULL);
15062 assert(_PyUnicode_CHECK(s));
15063#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015064 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015065 return;
15066#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015067 /* If it's a subclass, we don't really know what putting
15068 it in the interned dict might do. */
15069 if (!PyUnicode_CheckExact(s))
15070 return;
15071 if (PyUnicode_CHECK_INTERNED(s))
15072 return;
15073 if (interned == NULL) {
15074 interned = PyDict_New();
15075 if (interned == NULL) {
15076 PyErr_Clear(); /* Don't leave an exception */
15077 return;
15078 }
15079 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015080 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015081 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015082 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015083 if (t == NULL) {
15084 PyErr_Clear();
15085 return;
15086 }
15087 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015088 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015089 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015090 return;
15091 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015092 /* The two references in interned are not counted by refcnt.
15093 The deallocator will take care of this */
15094 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015095 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015096}
15097
15098void
15099PyUnicode_InternImmortal(PyObject **p)
15100{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015101 PyUnicode_InternInPlace(p);
15102 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015103 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015104 Py_INCREF(*p);
15105 }
Walter Dörwald16807132007-05-25 13:52:07 +000015106}
15107
15108PyObject *
15109PyUnicode_InternFromString(const char *cp)
15110{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015111 PyObject *s = PyUnicode_FromString(cp);
15112 if (s == NULL)
15113 return NULL;
15114 PyUnicode_InternInPlace(&s);
15115 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015116}
15117
Alexander Belopolsky40018472011-02-26 01:02:56 +000015118void
15119_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015120{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015121 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015122 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 Py_ssize_t i, n;
15124 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015125
Benjamin Peterson14339b62009-01-31 16:36:08 +000015126 if (interned == NULL || !PyDict_Check(interned))
15127 return;
15128 keys = PyDict_Keys(interned);
15129 if (keys == NULL || !PyList_Check(keys)) {
15130 PyErr_Clear();
15131 return;
15132 }
Walter Dörwald16807132007-05-25 13:52:07 +000015133
Benjamin Peterson14339b62009-01-31 16:36:08 +000015134 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15135 detector, interned unicode strings are not forcibly deallocated;
15136 rather, we give them their stolen references back, and then clear
15137 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015138
Benjamin Peterson14339b62009-01-31 16:36:08 +000015139 n = PyList_GET_SIZE(keys);
15140 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015141 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015142 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015143 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015144 if (PyUnicode_READY(s) == -1) {
15145 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015146 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015148 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015149 case SSTATE_NOT_INTERNED:
15150 /* XXX Shouldn't happen */
15151 break;
15152 case SSTATE_INTERNED_IMMORTAL:
15153 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015154 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015155 break;
15156 case SSTATE_INTERNED_MORTAL:
15157 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015158 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015159 break;
15160 default:
15161 Py_FatalError("Inconsistent interned string state.");
15162 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015163 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015164 }
15165 fprintf(stderr, "total size of all interned strings: "
15166 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15167 "mortal/immortal\n", mortal_size, immortal_size);
15168 Py_DECREF(keys);
15169 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015170 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015171}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015172
15173
15174/********************* Unicode Iterator **************************/
15175
15176typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 PyObject_HEAD
15178 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015179 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015180} unicodeiterobject;
15181
15182static void
15183unicodeiter_dealloc(unicodeiterobject *it)
15184{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015185 _PyObject_GC_UNTRACK(it);
15186 Py_XDECREF(it->it_seq);
15187 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015188}
15189
15190static int
15191unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15192{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015193 Py_VISIT(it->it_seq);
15194 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015195}
15196
15197static PyObject *
15198unicodeiter_next(unicodeiterobject *it)
15199{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015200 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015201
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 assert(it != NULL);
15203 seq = it->it_seq;
15204 if (seq == NULL)
15205 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015206 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015208 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15209 int kind = PyUnicode_KIND(seq);
15210 void *data = PyUnicode_DATA(seq);
15211 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15212 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015213 if (item != NULL)
15214 ++it->it_index;
15215 return item;
15216 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015217
Benjamin Peterson14339b62009-01-31 16:36:08 +000015218 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015219 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015220 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015221}
15222
15223static PyObject *
15224unicodeiter_len(unicodeiterobject *it)
15225{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015226 Py_ssize_t len = 0;
15227 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015228 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015229 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015230}
15231
15232PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15233
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015234static PyObject *
15235unicodeiter_reduce(unicodeiterobject *it)
15236{
15237 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015238 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015239 it->it_seq, it->it_index);
15240 } else {
15241 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15242 if (u == NULL)
15243 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015244 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015245 }
15246}
15247
15248PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15249
15250static PyObject *
15251unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15252{
15253 Py_ssize_t index = PyLong_AsSsize_t(state);
15254 if (index == -1 && PyErr_Occurred())
15255 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015256 if (it->it_seq != NULL) {
15257 if (index < 0)
15258 index = 0;
15259 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15260 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15261 it->it_index = index;
15262 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015263 Py_RETURN_NONE;
15264}
15265
15266PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15267
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015268static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015269 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015270 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015271 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15272 reduce_doc},
15273 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15274 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015275 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015276};
15277
15278PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015279 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15280 "str_iterator", /* tp_name */
15281 sizeof(unicodeiterobject), /* tp_basicsize */
15282 0, /* tp_itemsize */
15283 /* methods */
15284 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15285 0, /* tp_print */
15286 0, /* tp_getattr */
15287 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015288 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015289 0, /* tp_repr */
15290 0, /* tp_as_number */
15291 0, /* tp_as_sequence */
15292 0, /* tp_as_mapping */
15293 0, /* tp_hash */
15294 0, /* tp_call */
15295 0, /* tp_str */
15296 PyObject_GenericGetAttr, /* tp_getattro */
15297 0, /* tp_setattro */
15298 0, /* tp_as_buffer */
15299 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15300 0, /* tp_doc */
15301 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15302 0, /* tp_clear */
15303 0, /* tp_richcompare */
15304 0, /* tp_weaklistoffset */
15305 PyObject_SelfIter, /* tp_iter */
15306 (iternextfunc)unicodeiter_next, /* tp_iternext */
15307 unicodeiter_methods, /* tp_methods */
15308 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015309};
15310
15311static PyObject *
15312unicode_iter(PyObject *seq)
15313{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015314 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015315
Benjamin Peterson14339b62009-01-31 16:36:08 +000015316 if (!PyUnicode_Check(seq)) {
15317 PyErr_BadInternalCall();
15318 return NULL;
15319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015320 if (PyUnicode_READY(seq) == -1)
15321 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015322 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15323 if (it == NULL)
15324 return NULL;
15325 it->it_index = 0;
15326 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015327 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015328 _PyObject_GC_TRACK(it);
15329 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015330}
15331
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015332
15333size_t
15334Py_UNICODE_strlen(const Py_UNICODE *u)
15335{
15336 int res = 0;
15337 while(*u++)
15338 res++;
15339 return res;
15340}
15341
15342Py_UNICODE*
15343Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15344{
15345 Py_UNICODE *u = s1;
15346 while ((*u++ = *s2++));
15347 return s1;
15348}
15349
15350Py_UNICODE*
15351Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15352{
15353 Py_UNICODE *u = s1;
15354 while ((*u++ = *s2++))
15355 if (n-- == 0)
15356 break;
15357 return s1;
15358}
15359
15360Py_UNICODE*
15361Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15362{
15363 Py_UNICODE *u1 = s1;
15364 u1 += Py_UNICODE_strlen(u1);
15365 Py_UNICODE_strcpy(u1, s2);
15366 return s1;
15367}
15368
15369int
15370Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15371{
15372 while (*s1 && *s2 && *s1 == *s2)
15373 s1++, s2++;
15374 if (*s1 && *s2)
15375 return (*s1 < *s2) ? -1 : +1;
15376 if (*s1)
15377 return 1;
15378 if (*s2)
15379 return -1;
15380 return 0;
15381}
15382
15383int
15384Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15385{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015386 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015387 for (; n != 0; n--) {
15388 u1 = *s1;
15389 u2 = *s2;
15390 if (u1 != u2)
15391 return (u1 < u2) ? -1 : +1;
15392 if (u1 == '\0')
15393 return 0;
15394 s1++;
15395 s2++;
15396 }
15397 return 0;
15398}
15399
15400Py_UNICODE*
15401Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15402{
15403 const Py_UNICODE *p;
15404 for (p = s; *p; p++)
15405 if (*p == c)
15406 return (Py_UNICODE*)p;
15407 return NULL;
15408}
15409
15410Py_UNICODE*
15411Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15412{
15413 const Py_UNICODE *p;
15414 p = s + Py_UNICODE_strlen(s);
15415 while (p != s) {
15416 p--;
15417 if (*p == c)
15418 return (Py_UNICODE*)p;
15419 }
15420 return NULL;
15421}
Victor Stinner331ea922010-08-10 16:37:20 +000015422
Victor Stinner71133ff2010-09-01 23:43:53 +000015423Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015424PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015425{
Victor Stinner577db2c2011-10-11 22:12:48 +020015426 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015427 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015429 if (!PyUnicode_Check(unicode)) {
15430 PyErr_BadArgument();
15431 return NULL;
15432 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015433 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015434 if (u == NULL)
15435 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015436 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015437 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015438 PyErr_NoMemory();
15439 return NULL;
15440 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015441 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015442 size *= sizeof(Py_UNICODE);
15443 copy = PyMem_Malloc(size);
15444 if (copy == NULL) {
15445 PyErr_NoMemory();
15446 return NULL;
15447 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015448 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015449 return copy;
15450}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015451
Georg Brandl66c221e2010-10-14 07:04:07 +000015452/* A _string module, to export formatter_parser and formatter_field_name_split
15453 to the string.Formatter class implemented in Python. */
15454
15455static PyMethodDef _string_methods[] = {
15456 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15457 METH_O, PyDoc_STR("split the argument as a field name")},
15458 {"formatter_parser", (PyCFunction) formatter_parser,
15459 METH_O, PyDoc_STR("parse the argument as a format string")},
15460 {NULL, NULL}
15461};
15462
15463static struct PyModuleDef _string_module = {
15464 PyModuleDef_HEAD_INIT,
15465 "_string",
15466 PyDoc_STR("string helper module"),
15467 0,
15468 _string_methods,
15469 NULL,
15470 NULL,
15471 NULL,
15472 NULL
15473};
15474
15475PyMODINIT_FUNC
15476PyInit__string(void)
15477{
15478 return PyModule_Create(&_string_module);
15479}
15480
15481
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015482#ifdef __cplusplus
15483}
15484#endif