blob: ce56b04e6dec06f915726284c55f49669f93f2e4 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043#include "internal/pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050045#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070046#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000047
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000048#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000049#include <windows.h>
50#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000051
Larry Hastings61272b72014-01-07 12:41:53 -080052/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090053class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080054[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090055/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
56
57/*[python input]
58class Py_UCS4_converter(CConverter):
59 type = 'Py_UCS4'
60 converter = 'convert_uc'
61
62 def converter_init(self):
63 if self.default is not unspecified:
64 self.c_default = ascii(self.default)
65 if len(self.c_default) > 4 or self.c_default[0] != "'":
66 self.c_default = hex(ord(self.default))
67
68[python start generated code]*/
69/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080070
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000071/* --- Globals ------------------------------------------------------------
72
Serhiy Storchaka05997252013-01-26 12:14:02 +020073NOTE: In the interpreter's initialization phase, some globals are currently
74 initialized dynamically as needed. In the process Unicode objects may
75 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000076
77*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000078
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079
80#ifdef __cplusplus
81extern "C" {
82#endif
83
Victor Stinner8faf8212011-12-08 22:14:11 +010084/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
85#define MAX_UNICODE 0x10ffff
86
Victor Stinner910337b2011-10-03 03:20:16 +020087#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020088# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020089#else
90# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
91#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020092
Victor Stinnere90fe6a2011-10-01 16:48:13 +020093#define _PyUnicode_UTF8(op) \
94 (((PyCompactUnicodeObject*)(op))->utf8)
95#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020096 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020097 assert(PyUnicode_IS_READY(op)), \
98 PyUnicode_IS_COMPACT_ASCII(op) ? \
99 ((char*)((PyASCIIObject*)(op) + 1)) : \
100 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200101#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 (((PyCompactUnicodeObject*)(op))->utf8_length)
103#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200104 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200105 assert(PyUnicode_IS_READY(op)), \
106 PyUnicode_IS_COMPACT_ASCII(op) ? \
107 ((PyASCIIObject*)(op))->length : \
108 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_WSTR(op) \
110 (((PyASCIIObject*)(op))->wstr)
111#define _PyUnicode_WSTR_LENGTH(op) \
112 (((PyCompactUnicodeObject*)(op))->wstr_length)
113#define _PyUnicode_LENGTH(op) \
114 (((PyASCIIObject *)(op))->length)
115#define _PyUnicode_STATE(op) \
116 (((PyASCIIObject *)(op))->state)
117#define _PyUnicode_HASH(op) \
118 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200125#define _PyUnicode_DATA_ANY(op) \
126 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200127
Victor Stinner910337b2011-10-03 03:20:16 +0200128#undef PyUnicode_READY
129#define PyUnicode_READY(op) \
130 (assert(_PyUnicode_CHECK(op)), \
131 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200132 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100133 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200134
Victor Stinnerc379ead2011-10-03 12:52:27 +0200135#define _PyUnicode_SHARE_UTF8(op) \
136 (assert(_PyUnicode_CHECK(op)), \
137 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
138 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
139#define _PyUnicode_SHARE_WSTR(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
142
Victor Stinner829c0ad2011-10-03 01:08:02 +0200143/* true if the Unicode object has an allocated UTF-8 memory block
144 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200145#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200146 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200147 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200148 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
149
Victor Stinner03490912011-10-03 23:45:12 +0200150/* true if the Unicode object has an allocated wstr memory block
151 (not shared with other data) */
152#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200153 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200154 (!PyUnicode_IS_READY(op) || \
155 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
156
Victor Stinner910337b2011-10-03 03:20:16 +0200157/* Generic helper macro to convert characters of different types.
158 from_type and to_type have to be valid type names, begin and end
159 are pointers to the source characters which should be of type
160 "from_type *". to is a pointer of type "to_type *" and points to the
161 buffer where the result characters are written to. */
162#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
163 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100164 to_type *_to = (to_type *)(to); \
165 const from_type *_iter = (from_type *)(begin); \
166 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200167 Py_ssize_t n = (_end) - (_iter); \
168 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200169 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_unrolled_end)) { \
171 _to[0] = (to_type) _iter[0]; \
172 _to[1] = (to_type) _iter[1]; \
173 _to[2] = (to_type) _iter[2]; \
174 _to[3] = (to_type) _iter[3]; \
175 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200176 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200177 while (_iter < (_end)) \
178 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200179 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200180
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200181#ifdef MS_WINDOWS
182 /* On Windows, overallocate by 50% is the best factor */
183# define OVERALLOCATE_FACTOR 2
184#else
185 /* On Linux, overallocate by 25% is the best factor */
186# define OVERALLOCATE_FACTOR 4
187#endif
188
Walter Dörwald16807132007-05-25 13:52:07 +0000189/* This dictionary holds all interned unicode strings. Note that references
190 to strings in this dictionary are *not* counted in the string's ob_refcnt.
191 When the interned string reaches a refcnt of 0 the string deallocation
192 function will delete the reference from this dictionary.
193
194 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000195 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000196*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000198
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200201
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200203 do { \
204 if (unicode_empty != NULL) \
205 Py_INCREF(unicode_empty); \
206 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207 unicode_empty = PyUnicode_New(0, 0); \
208 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200209 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200210 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
211 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200213 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000214
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215#define _Py_RETURN_UNICODE_EMPTY() \
216 do { \
217 _Py_INCREF_UNICODE_EMPTY(); \
218 return unicode_empty; \
219 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000220
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200221/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700222static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200223_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
224
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200225/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200226static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200227
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000228/* Single character Unicode strings in the Latin-1 range are being
229 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200230static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000231
Christian Heimes190d79e2008-01-30 11:58:22 +0000232/* Fast detection of the most frequent whitespace characters */
233const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000235/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000236/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000237/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000238/* case 0x000C: * FORM FEED */
239/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000240 0, 1, 1, 1, 1, 1, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000242/* case 0x001C: * FILE SEPARATOR */
243/* case 0x001D: * GROUP SEPARATOR */
244/* case 0x001E: * RECORD SEPARATOR */
245/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000246 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000247/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000248 1, 0, 0, 0, 0, 0, 0, 0,
249 0, 0, 0, 0, 0, 0, 0, 0,
250 0, 0, 0, 0, 0, 0, 0, 0,
251 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000252
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
254 0, 0, 0, 0, 0, 0, 0, 0,
255 0, 0, 0, 0, 0, 0, 0, 0,
256 0, 0, 0, 0, 0, 0, 0, 0,
257 0, 0, 0, 0, 0, 0, 0, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000261};
262
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200263/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200264static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200265static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100266static int unicode_modifiable(PyObject *unicode);
267
Victor Stinnerfe226c02011-10-03 03:52:20 +0200268
Alexander Belopolsky40018472011-02-26 01:02:56 +0000269static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100270_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200271static PyObject *
272_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
273static PyObject *
274_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
275
276static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000277unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000278 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100279 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000280 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
281
Alexander Belopolsky40018472011-02-26 01:02:56 +0000282static void
283raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300284 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100285 PyObject *unicode,
286 Py_ssize_t startpos, Py_ssize_t endpos,
287 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000288
Christian Heimes190d79e2008-01-30 11:58:22 +0000289/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200290static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000292/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000293/* 0x000B, * LINE TABULATION */
294/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000295/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000296 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000298/* 0x001C, * FILE SEPARATOR */
299/* 0x001D, * GROUP SEPARATOR */
300/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 0, 0, 0, 0, 1, 1, 1, 0,
302 0, 0, 0, 0, 0, 0, 0, 0,
303 0, 0, 0, 0, 0, 0, 0, 0,
304 0, 0, 0, 0, 0, 0, 0, 0,
305 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000306
Benjamin Peterson14339b62009-01-31 16:36:08 +0000307 0, 0, 0, 0, 0, 0, 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0,
309 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0, 0, 0, 0, 0,
311 0, 0, 0, 0, 0, 0, 0, 0,
312 0, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0,
314 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000315};
316
INADA Naoki3ae20562017-01-16 20:41:20 +0900317static int convert_uc(PyObject *obj, void *addr);
318
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300319#include "clinic/unicodeobject.c.h"
320
Victor Stinner50149202015-09-22 00:26:54 +0200321typedef enum {
322 _Py_ERROR_UNKNOWN=0,
323 _Py_ERROR_STRICT,
324 _Py_ERROR_SURROGATEESCAPE,
325 _Py_ERROR_REPLACE,
326 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200327 _Py_ERROR_BACKSLASHREPLACE,
328 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200329 _Py_ERROR_XMLCHARREFREPLACE,
330 _Py_ERROR_OTHER
331} _Py_error_handler;
332
333static _Py_error_handler
334get_error_handler(const char *errors)
335{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200337 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200338 }
339 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200341 }
342 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200343 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200344 }
345 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200346 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200347 }
348 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200349 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200350 }
351 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200352 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200353 }
354 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200355 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200356 }
Victor Stinner50149202015-09-22 00:26:54 +0200357 return _Py_ERROR_OTHER;
358}
359
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300360/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
361 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000362Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000363PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000364{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000365#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000366 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000367#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000368 /* This is actually an illegal character, so it should
369 not be passed to unichr. */
370 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000371#endif
372}
373
Victor Stinner910337b2011-10-03 03:20:16 +0200374#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200375int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100376_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200377{
378 PyASCIIObject *ascii;
379 unsigned int kind;
380
381 assert(PyUnicode_Check(op));
382
383 ascii = (PyASCIIObject *)op;
384 kind = ascii->state.kind;
385
Victor Stinnera3b334d2011-10-03 13:53:37 +0200386 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200387 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 assert(ascii->state.ready == 1);
389 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200391 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200392 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200393
Victor Stinnera41463c2011-10-04 01:05:08 +0200394 if (ascii->state.compact == 1) {
395 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200396 assert(kind == PyUnicode_1BYTE_KIND
397 || kind == PyUnicode_2BYTE_KIND
398 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200399 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200400 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200401 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100402 }
403 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200404 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
405
406 data = unicode->data.any;
407 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100408 assert(ascii->length == 0);
409 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200410 assert(ascii->state.compact == 0);
411 assert(ascii->state.ascii == 0);
412 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100413 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200414 assert(ascii->wstr != NULL);
415 assert(data == NULL);
416 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 }
418 else {
419 assert(kind == PyUnicode_1BYTE_KIND
420 || kind == PyUnicode_2BYTE_KIND
421 || kind == PyUnicode_4BYTE_KIND);
422 assert(ascii->state.compact == 0);
423 assert(ascii->state.ready == 1);
424 assert(data != NULL);
425 if (ascii->state.ascii) {
426 assert (compact->utf8 == data);
427 assert (compact->utf8_length == ascii->length);
428 }
429 else
430 assert (compact->utf8 != data);
431 }
432 }
433 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200434 if (
435#if SIZEOF_WCHAR_T == 2
436 kind == PyUnicode_2BYTE_KIND
437#else
438 kind == PyUnicode_4BYTE_KIND
439#endif
440 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200441 {
442 assert(ascii->wstr == data);
443 assert(compact->wstr_length == ascii->length);
444 } else
445 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200446 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200447
448 if (compact->utf8 == NULL)
449 assert(compact->utf8_length == 0);
450 if (ascii->wstr == NULL)
451 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200452 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 /* check that the best kind is used */
454 if (check_content && kind != PyUnicode_WCHAR_KIND)
455 {
456 Py_ssize_t i;
457 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200458 void *data;
459 Py_UCS4 ch;
460
461 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200462 for (i=0; i < ascii->length; i++)
463 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200464 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200465 if (ch > maxchar)
466 maxchar = ch;
467 }
468 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100469 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200470 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100471 assert(maxchar <= 255);
472 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200473 else
474 assert(maxchar < 128);
475 }
Victor Stinner77faf692011-11-20 18:56:05 +0100476 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200477 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100478 assert(maxchar <= 0xFFFF);
479 }
480 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200481 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100482 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100483 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200484 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200485 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400486 return 1;
487}
Victor Stinner910337b2011-10-03 03:20:16 +0200488#endif
489
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100490static PyObject*
491unicode_result_wchar(PyObject *unicode)
492{
493#ifndef Py_DEBUG
494 Py_ssize_t len;
495
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 len = _PyUnicode_WSTR_LENGTH(unicode);
497 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100498 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200499 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100500 }
501
502 if (len == 1) {
503 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100504 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100505 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
506 Py_DECREF(unicode);
507 return latin1_char;
508 }
509 }
510
511 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200512 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100513 return NULL;
514 }
515#else
Victor Stinneraa771272012-10-04 02:32:58 +0200516 assert(Py_REFCNT(unicode) == 1);
517
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 /* don't make the result ready in debug mode to ensure that the caller
519 makes the string ready before using it */
520 assert(_PyUnicode_CheckConsistency(unicode, 1));
521#endif
522 return unicode;
523}
524
525static PyObject*
526unicode_result_ready(PyObject *unicode)
527{
528 Py_ssize_t length;
529
530 length = PyUnicode_GET_LENGTH(unicode);
531 if (length == 0) {
532 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100533 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200534 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100535 }
536 return unicode_empty;
537 }
538
539 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200540 void *data = PyUnicode_DATA(unicode);
541 int kind = PyUnicode_KIND(unicode);
542 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100543 if (ch < 256) {
544 PyObject *latin1_char = unicode_latin1[ch];
545 if (latin1_char != NULL) {
546 if (unicode != latin1_char) {
547 Py_INCREF(latin1_char);
548 Py_DECREF(unicode);
549 }
550 return latin1_char;
551 }
552 else {
553 assert(_PyUnicode_CheckConsistency(unicode, 1));
554 Py_INCREF(unicode);
555 unicode_latin1[ch] = unicode;
556 return unicode;
557 }
558 }
559 }
560
561 assert(_PyUnicode_CheckConsistency(unicode, 1));
562 return unicode;
563}
564
565static PyObject*
566unicode_result(PyObject *unicode)
567{
568 assert(_PyUnicode_CHECK(unicode));
569 if (PyUnicode_IS_READY(unicode))
570 return unicode_result_ready(unicode);
571 else
572 return unicode_result_wchar(unicode);
573}
574
Victor Stinnerc4b49542011-12-11 22:44:26 +0100575static PyObject*
576unicode_result_unchanged(PyObject *unicode)
577{
578 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500579 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100580 return NULL;
581 Py_INCREF(unicode);
582 return unicode;
583 }
584 else
585 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100586 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100587}
588
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200589/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
590 ASCII, Latin1, UTF-8, etc. */
591static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200592backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
594{
Victor Stinnerad771582015-10-09 12:38:53 +0200595 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200596 Py_UCS4 ch;
597 enum PyUnicode_Kind kind;
598 void *data;
599
600 assert(PyUnicode_IS_READY(unicode));
601 kind = PyUnicode_KIND(unicode);
602 data = PyUnicode_DATA(unicode);
603
604 size = 0;
605 /* determine replacement size */
606 for (i = collstart; i < collend; ++i) {
607 Py_ssize_t incr;
608
609 ch = PyUnicode_READ(kind, data, i);
610 if (ch < 0x100)
611 incr = 2+2;
612 else if (ch < 0x10000)
613 incr = 2+4;
614 else {
615 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200616 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200617 }
618 if (size > PY_SSIZE_T_MAX - incr) {
619 PyErr_SetString(PyExc_OverflowError,
620 "encoded result is too long for a Python string");
621 return NULL;
622 }
623 size += incr;
624 }
625
Victor Stinnerad771582015-10-09 12:38:53 +0200626 str = _PyBytesWriter_Prepare(writer, str, size);
627 if (str == NULL)
628 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200629
630 /* generate replacement */
631 for (i = collstart; i < collend; ++i) {
632 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200633 *str++ = '\\';
634 if (ch >= 0x00010000) {
635 *str++ = 'U';
636 *str++ = Py_hexdigits[(ch>>28)&0xf];
637 *str++ = Py_hexdigits[(ch>>24)&0xf];
638 *str++ = Py_hexdigits[(ch>>20)&0xf];
639 *str++ = Py_hexdigits[(ch>>16)&0xf];
640 *str++ = Py_hexdigits[(ch>>12)&0xf];
641 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200642 }
Victor Stinner797485e2015-10-09 03:17:30 +0200643 else if (ch >= 0x100) {
644 *str++ = 'u';
645 *str++ = Py_hexdigits[(ch>>12)&0xf];
646 *str++ = Py_hexdigits[(ch>>8)&0xf];
647 }
648 else
649 *str++ = 'x';
650 *str++ = Py_hexdigits[(ch>>4)&0xf];
651 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200652 }
653 return str;
654}
655
656/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
657 ASCII, Latin1, UTF-8, etc. */
658static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200659xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200660 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
661{
Victor Stinnerad771582015-10-09 12:38:53 +0200662 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200663 Py_UCS4 ch;
664 enum PyUnicode_Kind kind;
665 void *data;
666
667 assert(PyUnicode_IS_READY(unicode));
668 kind = PyUnicode_KIND(unicode);
669 data = PyUnicode_DATA(unicode);
670
671 size = 0;
672 /* determine replacement size */
673 for (i = collstart; i < collend; ++i) {
674 Py_ssize_t incr;
675
676 ch = PyUnicode_READ(kind, data, i);
677 if (ch < 10)
678 incr = 2+1+1;
679 else if (ch < 100)
680 incr = 2+2+1;
681 else if (ch < 1000)
682 incr = 2+3+1;
683 else if (ch < 10000)
684 incr = 2+4+1;
685 else if (ch < 100000)
686 incr = 2+5+1;
687 else if (ch < 1000000)
688 incr = 2+6+1;
689 else {
690 assert(ch <= MAX_UNICODE);
691 incr = 2+7+1;
692 }
693 if (size > PY_SSIZE_T_MAX - incr) {
694 PyErr_SetString(PyExc_OverflowError,
695 "encoded result is too long for a Python string");
696 return NULL;
697 }
698 size += incr;
699 }
700
Victor Stinnerad771582015-10-09 12:38:53 +0200701 str = _PyBytesWriter_Prepare(writer, str, size);
702 if (str == NULL)
703 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200704
705 /* generate replacement */
706 for (i = collstart; i < collend; ++i) {
707 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
708 }
709 return str;
710}
711
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712/* --- Bloom Filters ----------------------------------------------------- */
713
714/* stuff to implement simple "bloom filters" for Unicode characters.
715 to keep things simple, we use a single bitmask, using the least 5
716 bits from each unicode characters as the bit index. */
717
718/* the linebreak mask is set up by Unicode_Init below */
719
Antoine Pitrouf068f942010-01-13 14:19:12 +0000720#if LONG_BIT >= 128
721#define BLOOM_WIDTH 128
722#elif LONG_BIT >= 64
723#define BLOOM_WIDTH 64
724#elif LONG_BIT >= 32
725#define BLOOM_WIDTH 32
726#else
727#error "LONG_BIT is smaller than 32"
728#endif
729
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730#define BLOOM_MASK unsigned long
731
Serhiy Storchaka05997252013-01-26 12:14:02 +0200732static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733
Antoine Pitrouf068f942010-01-13 14:19:12 +0000734#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735
Benjamin Peterson29060642009-01-31 22:14:21 +0000736#define BLOOM_LINEBREAK(ch) \
737 ((ch) < 128U ? ascii_linebreak[(ch)] : \
738 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700740static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742{
Victor Stinnera85af502013-04-09 21:53:54 +0200743#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
744 do { \
745 TYPE *data = (TYPE *)PTR; \
746 TYPE *end = data + LEN; \
747 Py_UCS4 ch; \
748 for (; data != end; data++) { \
749 ch = *data; \
750 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
751 } \
752 break; \
753 } while (0)
754
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755 /* calculate simple bloom-style bitmask for a given unicode string */
756
Antoine Pitrouf068f942010-01-13 14:19:12 +0000757 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
759 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200760 switch (kind) {
761 case PyUnicode_1BYTE_KIND:
762 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
763 break;
764 case PyUnicode_2BYTE_KIND:
765 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
766 break;
767 case PyUnicode_4BYTE_KIND:
768 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
769 break;
770 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700771 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200772 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200774
775#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776}
777
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300778static int
779ensure_unicode(PyObject *obj)
780{
781 if (!PyUnicode_Check(obj)) {
782 PyErr_Format(PyExc_TypeError,
783 "must be str, not %.100s",
784 Py_TYPE(obj)->tp_name);
785 return -1;
786 }
787 return PyUnicode_READY(obj);
788}
789
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200790/* Compilation of templated routines */
791
792#include "stringlib/asciilib.h"
793#include "stringlib/fastsearch.h"
794#include "stringlib/partition.h"
795#include "stringlib/split.h"
796#include "stringlib/count.h"
797#include "stringlib/find.h"
798#include "stringlib/find_max_char.h"
799#include "stringlib/localeutil.h"
800#include "stringlib/undef.h"
801
802#include "stringlib/ucs1lib.h"
803#include "stringlib/fastsearch.h"
804#include "stringlib/partition.h"
805#include "stringlib/split.h"
806#include "stringlib/count.h"
807#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300808#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200809#include "stringlib/find_max_char.h"
810#include "stringlib/localeutil.h"
811#include "stringlib/undef.h"
812
813#include "stringlib/ucs2lib.h"
814#include "stringlib/fastsearch.h"
815#include "stringlib/partition.h"
816#include "stringlib/split.h"
817#include "stringlib/count.h"
818#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300819#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200820#include "stringlib/find_max_char.h"
821#include "stringlib/localeutil.h"
822#include "stringlib/undef.h"
823
824#include "stringlib/ucs4lib.h"
825#include "stringlib/fastsearch.h"
826#include "stringlib/partition.h"
827#include "stringlib/split.h"
828#include "stringlib/count.h"
829#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300830#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200831#include "stringlib/find_max_char.h"
832#include "stringlib/localeutil.h"
833#include "stringlib/undef.h"
834
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200835#include "stringlib/unicodedefs.h"
836#include "stringlib/fastsearch.h"
837#include "stringlib/count.h"
838#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100839#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200840
Guido van Rossumd57fd912000-03-10 22:53:23 +0000841/* --- Unicode Object ----------------------------------------------------- */
842
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700843static inline Py_ssize_t
844findchar(const void *s, int kind,
845 Py_ssize_t size, Py_UCS4 ch,
846 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200847{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 switch (kind) {
849 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if ((Py_UCS1) ch != ch)
851 return -1;
852 if (direction > 0)
853 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
854 else
855 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200856 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200857 if ((Py_UCS2) ch != ch)
858 return -1;
859 if (direction > 0)
860 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
861 else
862 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200863 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200864 if (direction > 0)
865 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
866 else
867 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200868 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700869 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871}
872
Victor Stinnerafffce42012-10-03 23:03:17 +0200873#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000874/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200875 earlier.
876
877 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
878 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
879 invalid character in Unicode 6.0. */
880static void
881unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
882{
883 int kind = PyUnicode_KIND(unicode);
884 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
885 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
886 if (length <= old_length)
887 return;
888 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
889}
890#endif
891
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892static PyObject*
893resize_compact(PyObject *unicode, Py_ssize_t length)
894{
895 Py_ssize_t char_size;
896 Py_ssize_t struct_size;
897 Py_ssize_t new_size;
898 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100899 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200900#ifdef Py_DEBUG
901 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
902#endif
903
Victor Stinner79891572012-05-03 13:43:07 +0200904 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100906 assert(PyUnicode_IS_COMPACT(unicode));
907
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200908 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100909 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200910 struct_size = sizeof(PyASCIIObject);
911 else
912 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200913 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200914
Victor Stinnerfe226c02011-10-03 03:52:20 +0200915 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
916 PyErr_NoMemory();
917 return NULL;
918 }
919 new_size = (struct_size + (length + 1) * char_size);
920
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200921 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
922 PyObject_DEL(_PyUnicode_UTF8(unicode));
923 _PyUnicode_UTF8(unicode) = NULL;
924 _PyUnicode_UTF8_LENGTH(unicode) = 0;
925 }
Victor Stinner84def372011-12-11 20:04:56 +0100926 _Py_DEC_REFTOTAL;
927 _Py_ForgetReference(unicode);
928
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300929 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100930 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100931 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 PyErr_NoMemory();
933 return NULL;
934 }
Victor Stinner84def372011-12-11 20:04:56 +0100935 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200936 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100937
Victor Stinnerfe226c02011-10-03 03:52:20 +0200938 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200939 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100941 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 _PyUnicode_WSTR_LENGTH(unicode) = length;
943 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100944 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
945 PyObject_DEL(_PyUnicode_WSTR(unicode));
946 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100947 if (!PyUnicode_IS_ASCII(unicode))
948 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100949 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200950#ifdef Py_DEBUG
951 unicode_fill_invalid(unicode, old_length);
952#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
954 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200955 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 return unicode;
957}
958
Alexander Belopolsky40018472011-02-26 01:02:56 +0000959static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200960resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000961{
Victor Stinner95663112011-10-04 01:03:50 +0200962 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100963 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000966
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 if (PyUnicode_IS_READY(unicode)) {
968 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200969 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200970 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200971#ifdef Py_DEBUG
972 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
973#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974
975 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200976 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200977 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
978 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979
980 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 new_size = (length + 1) * char_size;
985
Victor Stinner7a9105a2011-12-12 00:13:42 +0100986 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
987 {
988 PyObject_DEL(_PyUnicode_UTF8(unicode));
989 _PyUnicode_UTF8(unicode) = NULL;
990 _PyUnicode_UTF8_LENGTH(unicode) = 0;
991 }
992
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 data = (PyObject *)PyObject_REALLOC(data, new_size);
994 if (data == NULL) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200999 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001001 _PyUnicode_WSTR_LENGTH(unicode) = length;
1002 }
1003 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001004 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001005 _PyUnicode_UTF8_LENGTH(unicode) = length;
1006 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001007 _PyUnicode_LENGTH(unicode) = length;
1008 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001009#ifdef Py_DEBUG
1010 unicode_fill_invalid(unicode, old_length);
1011#endif
Victor Stinner95663112011-10-04 01:03:50 +02001012 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001013 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001015 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001016 }
Victor Stinner95663112011-10-04 01:03:50 +02001017 assert(_PyUnicode_WSTR(unicode) != NULL);
1018
1019 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001020 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001021 PyErr_NoMemory();
1022 return -1;
1023 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001024 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001025 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001026 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001027 if (!wstr) {
1028 PyErr_NoMemory();
1029 return -1;
1030 }
1031 _PyUnicode_WSTR(unicode) = wstr;
1032 _PyUnicode_WSTR(unicode)[length] = 0;
1033 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001034 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001035 return 0;
1036}
1037
Victor Stinnerfe226c02011-10-03 03:52:20 +02001038static PyObject*
1039resize_copy(PyObject *unicode, Py_ssize_t length)
1040{
1041 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001042 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001045 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046
1047 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1048 if (copy == NULL)
1049 return NULL;
1050
1051 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001052 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001054 }
1055 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001056 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001057
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001058 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001059 if (w == NULL)
1060 return NULL;
1061 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1062 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001063 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001064 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001065 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001066 }
1067}
1068
Guido van Rossumd57fd912000-03-10 22:53:23 +00001069/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001070 Ux0000 terminated; some code (e.g. new_identifier)
1071 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072
1073 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001074 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075
1076*/
1077
Alexander Belopolsky40018472011-02-26 01:02:56 +00001078static PyUnicodeObject *
1079_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001080{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001081 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001083
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 if (length == 0 && unicode_empty != NULL) {
1086 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001087 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001088 }
1089
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001090 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001091 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001092 return (PyUnicodeObject *)PyErr_NoMemory();
1093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 if (length < 0) {
1095 PyErr_SetString(PyExc_SystemError,
1096 "Negative size passed to _PyUnicode_New");
1097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001098 }
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1101 if (unicode == NULL)
1102 return NULL;
1103 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001104
1105 _PyUnicode_WSTR_LENGTH(unicode) = length;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
1108 _PyUnicode_STATE(unicode).kind = 0;
1109 _PyUnicode_STATE(unicode).compact = 0;
1110 _PyUnicode_STATE(unicode).ready = 0;
1111 _PyUnicode_STATE(unicode).ascii = 0;
1112 _PyUnicode_DATA_ANY(unicode) = NULL;
1113 _PyUnicode_LENGTH(unicode) = 0;
1114 _PyUnicode_UTF8(unicode) = NULL;
1115 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1118 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001119 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001120 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001121 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123
Jeremy Hyltond8082792003-09-16 19:41:39 +00001124 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001125 * the caller fails before initializing str -- unicode_resize()
1126 * reads str[0], and the Keep-Alive optimization can keep memory
1127 * allocated for str alive across a call to unicode_dealloc(unicode).
1128 * We don't want unicode_resize to read uninitialized memory in
1129 * that case.
1130 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131 _PyUnicode_WSTR(unicode)[0] = 0;
1132 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001133
Victor Stinner7931d9a2011-11-04 00:22:48 +01001134 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001135 return unicode;
1136}
1137
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138static const char*
1139unicode_kind_name(PyObject *unicode)
1140{
Victor Stinner42dfd712011-10-03 14:41:45 +02001141 /* don't check consistency: unicode_kind_name() is called from
1142 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001143 if (!PyUnicode_IS_COMPACT(unicode))
1144 {
1145 if (!PyUnicode_IS_READY(unicode))
1146 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001147 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001148 {
1149 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001150 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 return "legacy ascii";
1152 else
1153 return "legacy latin1";
1154 case PyUnicode_2BYTE_KIND:
1155 return "legacy UCS2";
1156 case PyUnicode_4BYTE_KIND:
1157 return "legacy UCS4";
1158 default:
1159 return "<legacy invalid kind>";
1160 }
1161 }
1162 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001163 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001164 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001165 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001166 return "ascii";
1167 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001168 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001169 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001170 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001171 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001172 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 default:
1174 return "<invalid compact kind>";
1175 }
1176}
1177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179/* Functions wrapping macros for use in debugger */
1180char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001181 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001182}
1183
1184void *_PyUnicode_compact_data(void *unicode) {
1185 return _PyUnicode_COMPACT_DATA(unicode);
1186}
1187void *_PyUnicode_data(void *unicode){
1188 printf("obj %p\n", unicode);
1189 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1190 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1191 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1192 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1193 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1194 return PyUnicode_DATA(unicode);
1195}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001196
1197void
1198_PyUnicode_Dump(PyObject *op)
1199{
1200 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001201 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1202 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1203 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001206 {
1207 if (ascii->state.ascii)
1208 data = (ascii + 1);
1209 else
1210 data = (compact + 1);
1211 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001212 else
1213 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001214 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1215 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001216
Victor Stinnera849a4b2011-10-03 12:12:11 +02001217 if (ascii->wstr == data)
1218 printf("shared ");
1219 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001220
Victor Stinnera3b334d2011-10-03 13:53:37 +02001221 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001222 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001223 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1224 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001225 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1226 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001227 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001228 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001229}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230#endif
1231
1232PyObject *
1233PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1234{
1235 PyObject *obj;
1236 PyCompactUnicodeObject *unicode;
1237 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001238 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001239 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 Py_ssize_t char_size;
1241 Py_ssize_t struct_size;
1242
1243 /* Optimization for empty strings */
1244 if (size == 0 && unicode_empty != NULL) {
1245 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001246 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 }
1248
Victor Stinner9e9d6892011-10-04 01:02:02 +02001249 is_ascii = 0;
1250 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 struct_size = sizeof(PyCompactUnicodeObject);
1252 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001253 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 char_size = 1;
1255 is_ascii = 1;
1256 struct_size = sizeof(PyASCIIObject);
1257 }
1258 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001259 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 char_size = 1;
1261 }
1262 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001263 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 char_size = 2;
1265 if (sizeof(wchar_t) == 2)
1266 is_sharing = 1;
1267 }
1268 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001269 if (maxchar > MAX_UNICODE) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "invalid maximum character passed to PyUnicode_New");
1272 return NULL;
1273 }
Victor Stinner8f825062012-04-27 13:55:39 +02001274 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 char_size = 4;
1276 if (sizeof(wchar_t) == 4)
1277 is_sharing = 1;
1278 }
1279
1280 /* Ensure we won't overflow the size. */
1281 if (size < 0) {
1282 PyErr_SetString(PyExc_SystemError,
1283 "Negative size passed to PyUnicode_New");
1284 return NULL;
1285 }
1286 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1287 return PyErr_NoMemory();
1288
1289 /* Duplicated allocation code from _PyObject_New() instead of a call to
1290 * PyObject_New() so we are able to allocate space for the object and
1291 * it's data buffer.
1292 */
1293 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1294 if (obj == NULL)
1295 return PyErr_NoMemory();
1296 obj = PyObject_INIT(obj, &PyUnicode_Type);
1297 if (obj == NULL)
1298 return NULL;
1299
1300 unicode = (PyCompactUnicodeObject *)obj;
1301 if (is_ascii)
1302 data = ((PyASCIIObject*)obj) + 1;
1303 else
1304 data = unicode + 1;
1305 _PyUnicode_LENGTH(unicode) = size;
1306 _PyUnicode_HASH(unicode) = -1;
1307 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001308 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 _PyUnicode_STATE(unicode).compact = 1;
1310 _PyUnicode_STATE(unicode).ready = 1;
1311 _PyUnicode_STATE(unicode).ascii = is_ascii;
1312 if (is_ascii) {
1313 ((char*)data)[size] = 0;
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 }
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((char*)data)[size] = 0;
1318 _PyUnicode_WSTR(unicode) = NULL;
1319 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001321 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 else {
1324 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001325 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001326 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001328 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001329 ((Py_UCS4*)data)[size] = 0;
1330 if (is_sharing) {
1331 _PyUnicode_WSTR_LENGTH(unicode) = size;
1332 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1333 }
1334 else {
1335 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1336 _PyUnicode_WSTR(unicode) = NULL;
1337 }
1338 }
Victor Stinner8f825062012-04-27 13:55:39 +02001339#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001340 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001341#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001342 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 return obj;
1344}
1345
1346#if SIZEOF_WCHAR_T == 2
1347/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1348 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001349 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350
1351 This function assumes that unicode can hold one more code point than wstr
1352 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001353static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001355 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356{
1357 const wchar_t *iter;
1358 Py_UCS4 *ucs4_out;
1359
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(unicode != NULL);
1361 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1363 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1364
1365 for (iter = begin; iter < end; ) {
1366 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1367 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001368 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1369 && (iter+1) < end
1370 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 {
Victor Stinner551ac952011-11-29 22:58:13 +01001372 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 iter += 2;
1374 }
1375 else {
1376 *ucs4_out++ = *iter;
1377 iter++;
1378 }
1379 }
1380 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1381 _PyUnicode_GET_LENGTH(unicode)));
1382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383}
1384#endif
1385
Victor Stinnercd9950f2011-10-02 00:34:53 +02001386static int
Victor Stinner488fa492011-12-12 00:01:39 +01001387unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001388{
Victor Stinner488fa492011-12-12 00:01:39 +01001389 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001390 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001391 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001392 return -1;
1393 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001394 return 0;
1395}
1396
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397static int
1398_copy_characters(PyObject *to, Py_ssize_t to_start,
1399 PyObject *from, Py_ssize_t from_start,
1400 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001402 unsigned int from_kind, to_kind;
1403 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404
Victor Stinneree4544c2012-05-09 22:24:08 +02001405 assert(0 <= how_many);
1406 assert(0 <= from_start);
1407 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001408 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001409 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001410 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerd3f08822012-05-29 12:57:52 +02001412 assert(PyUnicode_Check(to));
1413 assert(PyUnicode_IS_READY(to));
1414 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1415
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001416 if (how_many == 0)
1417 return 0;
1418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001420 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423
Victor Stinnerf1852262012-06-16 16:38:26 +02001424#ifdef Py_DEBUG
1425 if (!check_maxchar
1426 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1427 {
1428 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1429 Py_UCS4 ch;
1430 Py_ssize_t i;
1431 for (i=0; i < how_many; i++) {
1432 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1433 assert(ch <= to_maxchar);
1434 }
1435 }
1436#endif
1437
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001438 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001439 if (check_maxchar
1440 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1441 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001442 /* Writing Latin-1 characters into an ASCII string requires to
1443 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001444 Py_UCS4 max_char;
1445 max_char = ucs1lib_find_max_char(from_data,
1446 (Py_UCS1*)from_data + how_many);
1447 if (max_char >= 128)
1448 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001449 }
Christian Heimesf051e432016-09-13 20:22:02 +02001450 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001451 (char*)from_data + from_kind * from_start,
1452 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001454 else if (from_kind == PyUnicode_1BYTE_KIND
1455 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS1, Py_UCS2,
1459 PyUnicode_1BYTE_DATA(from) + from_start,
1460 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_2BYTE_DATA(to) + to_start
1462 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001463 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001464 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001465 && to_kind == PyUnicode_4BYTE_KIND)
1466 {
1467 _PyUnicode_CONVERT_BYTES(
1468 Py_UCS1, Py_UCS4,
1469 PyUnicode_1BYTE_DATA(from) + from_start,
1470 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1471 PyUnicode_4BYTE_DATA(to) + to_start
1472 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001473 }
1474 else if (from_kind == PyUnicode_2BYTE_KIND
1475 && to_kind == PyUnicode_4BYTE_KIND)
1476 {
1477 _PyUnicode_CONVERT_BYTES(
1478 Py_UCS2, Py_UCS4,
1479 PyUnicode_2BYTE_DATA(from) + from_start,
1480 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1481 PyUnicode_4BYTE_DATA(to) + to_start
1482 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001483 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001484 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001485 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1486
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001487 if (!check_maxchar) {
1488 if (from_kind == PyUnicode_2BYTE_KIND
1489 && to_kind == PyUnicode_1BYTE_KIND)
1490 {
1491 _PyUnicode_CONVERT_BYTES(
1492 Py_UCS2, Py_UCS1,
1493 PyUnicode_2BYTE_DATA(from) + from_start,
1494 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1495 PyUnicode_1BYTE_DATA(to) + to_start
1496 );
1497 }
1498 else if (from_kind == PyUnicode_4BYTE_KIND
1499 && to_kind == PyUnicode_1BYTE_KIND)
1500 {
1501 _PyUnicode_CONVERT_BYTES(
1502 Py_UCS4, Py_UCS1,
1503 PyUnicode_4BYTE_DATA(from) + from_start,
1504 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1505 PyUnicode_1BYTE_DATA(to) + to_start
1506 );
1507 }
1508 else if (from_kind == PyUnicode_4BYTE_KIND
1509 && to_kind == PyUnicode_2BYTE_KIND)
1510 {
1511 _PyUnicode_CONVERT_BYTES(
1512 Py_UCS4, Py_UCS2,
1513 PyUnicode_4BYTE_DATA(from) + from_start,
1514 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1515 PyUnicode_2BYTE_DATA(to) + to_start
1516 );
1517 }
1518 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001519 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001520 }
1521 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001522 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001523 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001525 Py_ssize_t i;
1526
Victor Stinnera0702ab2011-09-29 14:14:38 +02001527 for (i=0; i < how_many; i++) {
1528 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001529 if (ch > to_maxchar)
1530 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001531 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1532 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001533 }
1534 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001535 return 0;
1536}
1537
Victor Stinnerd3f08822012-05-29 12:57:52 +02001538void
1539_PyUnicode_FastCopyCharacters(
1540 PyObject *to, Py_ssize_t to_start,
1541 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001542{
1543 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1544}
1545
1546Py_ssize_t
1547PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1548 PyObject *from, Py_ssize_t from_start,
1549 Py_ssize_t how_many)
1550{
1551 int err;
1552
1553 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1554 PyErr_BadInternalCall();
1555 return -1;
1556 }
1557
Benjamin Petersonbac79492012-01-14 13:34:47 -05001558 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001560 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001561 return -1;
1562
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001563 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001564 PyErr_SetString(PyExc_IndexError, "string index out of range");
1565 return -1;
1566 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001567 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568 PyErr_SetString(PyExc_IndexError, "string index out of range");
1569 return -1;
1570 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001571 if (how_many < 0) {
1572 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1573 return -1;
1574 }
1575 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1577 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001578 "Cannot write %zi characters at %zi "
1579 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001580 how_many, to_start, PyUnicode_GET_LENGTH(to));
1581 return -1;
1582 }
1583
1584 if (how_many == 0)
1585 return 0;
1586
Victor Stinner488fa492011-12-12 00:01:39 +01001587 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001588 return -1;
1589
1590 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1591 if (err) {
1592 PyErr_Format(PyExc_SystemError,
1593 "Cannot copy %s characters "
1594 "into a string of %s characters",
1595 unicode_kind_name(from),
1596 unicode_kind_name(to));
1597 return -1;
1598 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001599 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600}
1601
Victor Stinner17222162011-09-28 22:15:37 +02001602/* Find the maximum code point and count the number of surrogate pairs so a
1603 correct string length can be computed before converting a string to UCS4.
1604 This function counts single surrogates as a character and not as a pair.
1605
1606 Return 0 on success, or -1 on error. */
1607static int
1608find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1609 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610{
1611 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001612 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613
Victor Stinnerc53be962011-10-02 21:33:54 +02001614 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 *num_surrogates = 0;
1616 *maxchar = 0;
1617
1618 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001620 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1621 && (iter+1) < end
1622 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1623 {
1624 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1625 ++(*num_surrogates);
1626 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001630 {
1631 ch = *iter;
1632 iter++;
1633 }
1634 if (ch > *maxchar) {
1635 *maxchar = ch;
1636 if (*maxchar > MAX_UNICODE) {
1637 PyErr_Format(PyExc_ValueError,
1638 "character U+%x is not in range [U+0000; U+10ffff]",
1639 ch);
1640 return -1;
1641 }
1642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 }
1644 return 0;
1645}
1646
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001647int
1648_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649{
1650 wchar_t *end;
1651 Py_UCS4 maxchar = 0;
1652 Py_ssize_t num_surrogates;
1653#if SIZEOF_WCHAR_T == 2
1654 Py_ssize_t length_wo_surrogates;
1655#endif
1656
Georg Brandl7597add2011-10-05 16:36:47 +02001657 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001658 strings were created using _PyObject_New() and where no canonical
1659 representation (the str field) has been set yet aka strings
1660 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001661 assert(_PyUnicode_CHECK(unicode));
1662 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001665 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001666 /* Actually, it should neither be interned nor be anything else: */
1667 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001670 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001671 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673
1674 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001675 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1676 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 PyErr_NoMemory();
1678 return -1;
1679 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001680 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001681 _PyUnicode_WSTR(unicode), end,
1682 PyUnicode_1BYTE_DATA(unicode));
1683 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1684 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1685 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1686 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001687 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001688 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001689 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 }
1691 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001692 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001695 }
1696 PyObject_FREE(_PyUnicode_WSTR(unicode));
1697 _PyUnicode_WSTR(unicode) = NULL;
1698 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1699 }
1700 /* In this case we might have to convert down from 4-byte native
1701 wchar_t to 2-byte unicode. */
1702 else if (maxchar < 65536) {
1703 assert(num_surrogates == 0 &&
1704 "FindMaxCharAndNumSurrogatePairs() messed up");
1705
Victor Stinner506f5922011-09-28 22:34:18 +02001706#if SIZEOF_WCHAR_T == 2
1707 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001709 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#else
1715 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001716 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001717 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001718 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyErr_NoMemory();
1720 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 }
Victor Stinner506f5922011-09-28 22:34:18 +02001722 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1723 _PyUnicode_WSTR(unicode), end,
1724 PyUnicode_2BYTE_DATA(unicode));
1725 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1726 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1727 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001728 _PyUnicode_UTF8(unicode) = NULL;
1729 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001730 PyObject_FREE(_PyUnicode_WSTR(unicode));
1731 _PyUnicode_WSTR(unicode) = NULL;
1732 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1733#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 }
1735 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1736 else {
1737#if SIZEOF_WCHAR_T == 2
1738 /* in case the native representation is 2-bytes, we need to allocate a
1739 new normalized 4-byte version. */
1740 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001741 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1742 PyErr_NoMemory();
1743 return -1;
1744 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001745 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1746 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyErr_NoMemory();
1748 return -1;
1749 }
1750 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001752 _PyUnicode_UTF8(unicode) = NULL;
1753 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001754 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001756 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 PyObject_FREE(_PyUnicode_WSTR(unicode));
1758 _PyUnicode_WSTR(unicode) = NULL;
1759 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1760#else
1761 assert(num_surrogates == 0);
1762
Victor Stinnerc3c74152011-10-02 20:39:55 +02001763 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001765 _PyUnicode_UTF8(unicode) = NULL;
1766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1768#endif
1769 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1770 }
1771 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001772 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 return 0;
1774}
1775
Alexander Belopolsky40018472011-02-26 01:02:56 +00001776static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001777unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001778{
Walter Dörwald16807132007-05-25 13:52:07 +00001779 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_NOT_INTERNED:
1781 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 case SSTATE_INTERNED_MORTAL:
1784 /* revive dead object temporarily for DelItem */
1785 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001786 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001787 Py_FatalError(
1788 "deletion of interned string failed");
1789 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001790
Benjamin Peterson29060642009-01-31 22:14:21 +00001791 case SSTATE_INTERNED_IMMORTAL:
1792 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001793 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001794
Benjamin Peterson29060642009-01-31 22:14:21 +00001795 default:
1796 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001797 }
1798
Victor Stinner03490912011-10-03 23:45:12 +02001799 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001801 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001802 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001803 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1804 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001806 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807}
1808
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001809#ifdef Py_DEBUG
1810static int
1811unicode_is_singleton(PyObject *unicode)
1812{
1813 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1814 if (unicode == unicode_empty)
1815 return 1;
1816 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1817 {
1818 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1819 if (ch < 256 && unicode_latin1[ch] == unicode)
1820 return 1;
1821 }
1822 return 0;
1823}
1824#endif
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826static int
Victor Stinner488fa492011-12-12 00:01:39 +01001827unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828{
Victor Stinner488fa492011-12-12 00:01:39 +01001829 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 if (Py_REFCNT(unicode) != 1)
1831 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001832 if (_PyUnicode_HASH(unicode) != -1)
1833 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001834 if (PyUnicode_CHECK_INTERNED(unicode))
1835 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001836 if (!PyUnicode_CheckExact(unicode))
1837 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001838#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001839 /* singleton refcount is greater than 1 */
1840 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001841#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 return 1;
1843}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845static int
1846unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1847{
1848 PyObject *unicode;
1849 Py_ssize_t old_length;
1850
1851 assert(p_unicode != NULL);
1852 unicode = *p_unicode;
1853
1854 assert(unicode != NULL);
1855 assert(PyUnicode_Check(unicode));
1856 assert(0 <= length);
1857
Victor Stinner910337b2011-10-03 03:20:16 +02001858 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 old_length = PyUnicode_WSTR_LENGTH(unicode);
1860 else
1861 old_length = PyUnicode_GET_LENGTH(unicode);
1862 if (old_length == length)
1863 return 0;
1864
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001865 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001866 _Py_INCREF_UNICODE_EMPTY();
1867 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001868 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001869 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001870 return 0;
1871 }
1872
Victor Stinner488fa492011-12-12 00:01:39 +01001873 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 PyObject *copy = resize_copy(unicode, length);
1875 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001877 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001878 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001879 }
1880
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001882 PyObject *new_unicode = resize_compact(unicode, length);
1883 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001885 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001886 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001887 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001888 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001889}
1890
Alexander Belopolsky40018472011-02-26 01:02:56 +00001891int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001892PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001894 PyObject *unicode;
1895 if (p_unicode == NULL) {
1896 PyErr_BadInternalCall();
1897 return -1;
1898 }
1899 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001900 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001901 {
1902 PyErr_BadInternalCall();
1903 return -1;
1904 }
1905 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001906}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001907
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001908/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001909
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001910 WARNING: The function doesn't copy the terminating null character and
1911 doesn't check the maximum character (may write a latin1 character in an
1912 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001913static void
1914unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1915 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001916{
1917 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1918 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001919 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001920
1921 switch (kind) {
1922 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001923 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001924#ifdef Py_DEBUG
1925 if (PyUnicode_IS_ASCII(unicode)) {
1926 Py_UCS4 maxchar = ucs1lib_find_max_char(
1927 (const Py_UCS1*)str,
1928 (const Py_UCS1*)str + len);
1929 assert(maxchar < 128);
1930 }
1931#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001932 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001933 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001934 }
1935 case PyUnicode_2BYTE_KIND: {
1936 Py_UCS2 *start = (Py_UCS2 *)data + index;
1937 Py_UCS2 *ucs2 = start;
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs2 = (Py_UCS2)*str;
1942
1943 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001944 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001945 }
1946 default: {
1947 Py_UCS4 *start = (Py_UCS4 *)data + index;
1948 Py_UCS4 *ucs4 = start;
1949 assert(kind == PyUnicode_4BYTE_KIND);
1950 assert(index <= PyUnicode_GET_LENGTH(unicode));
1951
Victor Stinner184252a2012-06-16 02:57:41 +02001952 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001953 *ucs4 = (Py_UCS4)*str;
1954
1955 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001956 }
1957 }
1958}
1959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960static PyObject*
1961get_latin1_char(unsigned char ch)
1962{
Victor Stinnera464fc12011-10-02 20:39:30 +02001963 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001964 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001965 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 if (!unicode)
1967 return NULL;
1968 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001969 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001970 unicode_latin1[ch] = unicode;
1971 }
1972 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001973 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974}
1975
Victor Stinner985a82a2014-01-03 12:53:47 +01001976static PyObject*
1977unicode_char(Py_UCS4 ch)
1978{
1979 PyObject *unicode;
1980
1981 assert(ch <= MAX_UNICODE);
1982
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001983 if (ch < 256)
1984 return get_latin1_char(ch);
1985
Victor Stinner985a82a2014-01-03 12:53:47 +01001986 unicode = PyUnicode_New(1, ch);
1987 if (unicode == NULL)
1988 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001989
1990 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1991 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001992 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001993 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001994 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1995 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1996 }
1997 assert(_PyUnicode_CheckConsistency(unicode, 1));
1998 return unicode;
1999}
2000
Alexander Belopolsky40018472011-02-26 01:02:56 +00002001PyObject *
2002PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002003{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002004 if (u == NULL)
2005 return (PyObject*)_PyUnicode_New(size);
2006
2007 if (size < 0) {
2008 PyErr_BadInternalCall();
2009 return NULL;
2010 }
2011
2012 return PyUnicode_FromWideChar(u, size);
2013}
2014
2015PyObject *
2016PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2017{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002018 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 Py_UCS4 maxchar = 0;
2020 Py_ssize_t num_surrogates;
2021
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002022 if (u == NULL && size != 0) {
2023 PyErr_BadInternalCall();
2024 return NULL;
2025 }
2026
2027 if (size == -1) {
2028 size = wcslen(u);
2029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002030
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002031 /* If the Unicode data is known at construction time, we can apply
2032 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002035 if (size == 0)
2036 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 /* Single character Unicode objects in the Latin-1 range are
2039 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002040 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return get_latin1_char((unsigned char)*u);
2042
2043 /* If not empty and not single character, copy the Unicode data
2044 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002045 if (find_maxchar_surrogates(u, u + size,
2046 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048
Victor Stinner8faf8212011-12-08 22:14:11 +01002049 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 if (!unicode)
2051 return NULL;
2052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 switch (PyUnicode_KIND(unicode)) {
2054 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002055 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2057 break;
2058 case PyUnicode_2BYTE_KIND:
2059#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002060 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002062 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2064#endif
2065 break;
2066 case PyUnicode_4BYTE_KIND:
2067#if SIZEOF_WCHAR_T == 2
2068 /* This is the only case which has to process surrogates, thus
2069 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002070 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071#else
2072 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002073 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074#endif
2075 break;
2076 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002077 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002080 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081}
2082
Alexander Belopolsky40018472011-02-26 01:02:56 +00002083PyObject *
2084PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002085{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002086 if (size < 0) {
2087 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002088 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002089 return NULL;
2090 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002091 if (u != NULL)
2092 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2093 else
2094 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002095}
2096
Alexander Belopolsky40018472011-02-26 01:02:56 +00002097PyObject *
2098PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002099{
2100 size_t size = strlen(u);
2101 if (size > PY_SSIZE_T_MAX) {
2102 PyErr_SetString(PyExc_OverflowError, "input too long");
2103 return NULL;
2104 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002105 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002106}
2107
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002108PyObject *
2109_PyUnicode_FromId(_Py_Identifier *id)
2110{
2111 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002112 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2113 strlen(id->string),
2114 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002115 if (!id->object)
2116 return NULL;
2117 PyUnicode_InternInPlace(&id->object);
2118 assert(!id->next);
2119 id->next = static_strings;
2120 static_strings = id;
2121 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002122 return id->object;
2123}
2124
2125void
2126_PyUnicode_ClearStaticStrings()
2127{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002128 _Py_Identifier *tmp, *s = static_strings;
2129 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002130 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002131 tmp = s->next;
2132 s->next = NULL;
2133 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002134 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002135 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002136}
2137
Benjamin Peterson0df54292012-03-26 14:50:32 -04002138/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139
Victor Stinnerd3f08822012-05-29 12:57:52 +02002140PyObject*
2141_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002142{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002143 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002144 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002145 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002146#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002147 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002148#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002149 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002150 }
Victor Stinner785938e2011-12-11 20:09:03 +01002151 unicode = PyUnicode_New(size, 127);
2152 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002153 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002154 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2155 assert(_PyUnicode_CheckConsistency(unicode, 1));
2156 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002157}
2158
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159static Py_UCS4
2160kind_maxchar_limit(unsigned int kind)
2161{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002162 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002163 case PyUnicode_1BYTE_KIND:
2164 return 0x80;
2165 case PyUnicode_2BYTE_KIND:
2166 return 0x100;
2167 case PyUnicode_4BYTE_KIND:
2168 return 0x10000;
2169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002171 }
2172}
2173
Victor Stinner702c7342011-10-05 13:50:52 +02002174static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002175_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002178 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002179
Serhiy Storchaka678db842013-01-26 12:16:36 +02002180 if (size == 0)
2181 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002182 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002183 if (size == 1)
2184 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002185
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002186 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 if (!res)
2189 return NULL;
2190 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002191 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002193}
2194
Victor Stinnere57b1c02011-09-28 22:20:48 +02002195static PyObject*
2196_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197{
2198 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002199 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002200
Serhiy Storchaka678db842013-01-26 12:16:36 +02002201 if (size == 0)
2202 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002203 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002204 if (size == 1)
2205 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002207 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002208 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 if (!res)
2210 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 else {
2214 _PyUnicode_CONVERT_BYTES(
2215 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2216 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002217 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return res;
2219}
2220
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221static PyObject*
2222_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223{
2224 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002225 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002226
Serhiy Storchaka678db842013-01-26 12:16:36 +02002227 if (size == 0)
2228 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002229 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002230 if (size == 1)
2231 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002233 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002234 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 if (!res)
2236 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002237 if (max_char < 256)
2238 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2239 PyUnicode_1BYTE_DATA(res));
2240 else if (max_char < 0x10000)
2241 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2242 PyUnicode_2BYTE_DATA(res));
2243 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002245 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 return res;
2247}
2248
2249PyObject*
2250PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2251{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002252 if (size < 0) {
2253 PyErr_SetString(PyExc_ValueError, "size must be positive");
2254 return NULL;
2255 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002256 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002258 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002260 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002262 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002263 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002264 PyErr_SetString(PyExc_SystemError, "invalid kind");
2265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267}
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269Py_UCS4
2270_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2271{
2272 enum PyUnicode_Kind kind;
2273 void *startptr, *endptr;
2274
2275 assert(PyUnicode_IS_READY(unicode));
2276 assert(0 <= start);
2277 assert(end <= PyUnicode_GET_LENGTH(unicode));
2278 assert(start <= end);
2279
2280 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2281 return PyUnicode_MAX_CHAR_VALUE(unicode);
2282
2283 if (start == end)
2284 return 127;
2285
Victor Stinner94d558b2012-04-27 22:26:58 +02002286 if (PyUnicode_IS_ASCII(unicode))
2287 return 127;
2288
Victor Stinnerece58de2012-04-23 23:36:38 +02002289 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002290 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002291 endptr = (char *)startptr + end * kind;
2292 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002293 switch(kind) {
2294 case PyUnicode_1BYTE_KIND:
2295 return ucs1lib_find_max_char(startptr, endptr);
2296 case PyUnicode_2BYTE_KIND:
2297 return ucs2lib_find_max_char(startptr, endptr);
2298 case PyUnicode_4BYTE_KIND:
2299 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002301 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002302 }
2303}
2304
Victor Stinner25a4b292011-10-06 12:31:55 +02002305/* Ensure that a string uses the most efficient storage, if it is not the
2306 case: create a new string with of the right kind. Write NULL into *p_unicode
2307 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002308static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002309unicode_adjust_maxchar(PyObject **p_unicode)
2310{
2311 PyObject *unicode, *copy;
2312 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002314 unsigned int kind;
2315
2316 assert(p_unicode != NULL);
2317 unicode = *p_unicode;
2318 assert(PyUnicode_IS_READY(unicode));
2319 if (PyUnicode_IS_ASCII(unicode))
2320 return;
2321
2322 len = PyUnicode_GET_LENGTH(unicode);
2323 kind = PyUnicode_KIND(unicode);
2324 if (kind == PyUnicode_1BYTE_KIND) {
2325 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002326 max_char = ucs1lib_find_max_char(u, u + len);
2327 if (max_char >= 128)
2328 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 }
2330 else if (kind == PyUnicode_2BYTE_KIND) {
2331 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002332 max_char = ucs2lib_find_max_char(u, u + len);
2333 if (max_char >= 256)
2334 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002335 }
2336 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002337 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002338 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002339 max_char = ucs4lib_find_max_char(u, u + len);
2340 if (max_char >= 0x10000)
2341 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002342 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002343 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002344 if (copy != NULL)
2345 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002346 Py_DECREF(unicode);
2347 *p_unicode = copy;
2348}
2349
Victor Stinner034f6cf2011-09-30 02:26:44 +02002350PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002351_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002352{
Victor Stinner87af4f22011-11-21 23:03:47 +01002353 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002355
Victor Stinner034f6cf2011-09-30 02:26:44 +02002356 if (!PyUnicode_Check(unicode)) {
2357 PyErr_BadInternalCall();
2358 return NULL;
2359 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002360 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002361 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002362
Victor Stinner87af4f22011-11-21 23:03:47 +01002363 length = PyUnicode_GET_LENGTH(unicode);
2364 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002365 if (!copy)
2366 return NULL;
2367 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2368
Christian Heimesf051e432016-09-13 20:22:02 +02002369 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002370 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002371 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002372 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002373}
2374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375
Victor Stinnerbc603d12011-10-02 01:00:40 +02002376/* Widen Unicode objects to larger buffers. Don't write terminating null
2377 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002378
2379void*
2380_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2381{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 Py_ssize_t len;
2383 void *result;
2384 unsigned int skind;
2385
Benjamin Petersonbac79492012-01-14 13:34:47 -05002386 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002387 return NULL;
2388
2389 len = PyUnicode_GET_LENGTH(s);
2390 skind = PyUnicode_KIND(s);
2391 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002395 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002396 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002397 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002398 if (!result)
2399 return PyErr_NoMemory();
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS2,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002407 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002408 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 if (!result)
2410 return PyErr_NoMemory();
2411 if (skind == PyUnicode_2BYTE_KIND) {
2412 _PyUnicode_CONVERT_BYTES(
2413 Py_UCS2, Py_UCS4,
2414 PyUnicode_2BYTE_DATA(s),
2415 PyUnicode_2BYTE_DATA(s) + len,
2416 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002418 else {
2419 assert(skind == PyUnicode_1BYTE_KIND);
2420 _PyUnicode_CONVERT_BYTES(
2421 Py_UCS1, Py_UCS4,
2422 PyUnicode_1BYTE_DATA(s),
2423 PyUnicode_1BYTE_DATA(s) + len,
2424 result);
2425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002427 default:
2428 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 }
Victor Stinner01698042011-10-04 00:04:26 +02002430 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 return NULL;
2432}
2433
2434static Py_UCS4*
2435as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2436 int copy_null)
2437{
2438 int kind;
2439 void *data;
2440 Py_ssize_t len, targetlen;
2441 if (PyUnicode_READY(string) == -1)
2442 return NULL;
2443 kind = PyUnicode_KIND(string);
2444 data = PyUnicode_DATA(string);
2445 len = PyUnicode_GET_LENGTH(string);
2446 targetlen = len;
2447 if (copy_null)
2448 targetlen++;
2449 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002450 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 if (!target) {
2452 PyErr_NoMemory();
2453 return NULL;
2454 }
2455 }
2456 else {
2457 if (targetsize < targetlen) {
2458 PyErr_Format(PyExc_SystemError,
2459 "string is longer than the buffer");
2460 if (copy_null && 0 < targetsize)
2461 target[0] = 0;
2462 return NULL;
2463 }
2464 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002465 if (kind == PyUnicode_1BYTE_KIND) {
2466 Py_UCS1 *start = (Py_UCS1 *) data;
2467 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002469 else if (kind == PyUnicode_2BYTE_KIND) {
2470 Py_UCS2 *start = (Py_UCS2 *) data;
2471 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2472 }
2473 else {
2474 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002475 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 if (copy_null)
2478 target[len] = 0;
2479 return target;
2480}
2481
2482Py_UCS4*
2483PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2484 int copy_null)
2485{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002486 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 PyErr_BadInternalCall();
2488 return NULL;
2489 }
2490 return as_ucs4(string, target, targetsize, copy_null);
2491}
2492
2493Py_UCS4*
2494PyUnicode_AsUCS4Copy(PyObject *string)
2495{
2496 return as_ucs4(string, NULL, 0, 1);
2497}
2498
Victor Stinner15a11362012-10-06 23:48:20 +02002499/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002500 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2501 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2502#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002503
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002504static int
2505unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2506 Py_ssize_t width, Py_ssize_t precision)
2507{
2508 Py_ssize_t length, fill, arglen;
2509 Py_UCS4 maxchar;
2510
2511 if (PyUnicode_READY(str) == -1)
2512 return -1;
2513
2514 length = PyUnicode_GET_LENGTH(str);
2515 if ((precision == -1 || precision >= length)
2516 && width <= length)
2517 return _PyUnicodeWriter_WriteStr(writer, str);
2518
2519 if (precision != -1)
2520 length = Py_MIN(precision, length);
2521
2522 arglen = Py_MAX(length, width);
2523 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2524 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2525 else
2526 maxchar = writer->maxchar;
2527
2528 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2529 return -1;
2530
2531 if (width > length) {
2532 fill = width - length;
2533 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2534 return -1;
2535 writer->pos += fill;
2536 }
2537
2538 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2539 str, 0, length);
2540 writer->pos += length;
2541 return 0;
2542}
2543
2544static int
2545unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2546 Py_ssize_t width, Py_ssize_t precision)
2547{
2548 /* UTF-8 */
2549 Py_ssize_t length;
2550 PyObject *unicode;
2551 int res;
2552
2553 length = strlen(str);
2554 if (precision != -1)
2555 length = Py_MIN(length, precision);
2556 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2557 if (unicode == NULL)
2558 return -1;
2559
2560 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2561 Py_DECREF(unicode);
2562 return res;
2563}
2564
Victor Stinner96865452011-03-01 23:44:09 +00002565static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002566unicode_fromformat_arg(_PyUnicodeWriter *writer,
2567 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002568{
Victor Stinnere215d962012-10-06 23:03:36 +02002569 const char *p;
2570 Py_ssize_t len;
2571 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 Py_ssize_t width;
2573 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002574 int longflag;
2575 int longlongflag;
2576 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002577 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002578
2579 p = f;
2580 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002581 zeropad = 0;
2582 if (*f == '0') {
2583 zeropad = 1;
2584 f++;
2585 }
Victor Stinner96865452011-03-01 23:44:09 +00002586
2587 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 width = -1;
2589 if (Py_ISDIGIT((unsigned)*f)) {
2590 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002591 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002592 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002594 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002596 return NULL;
2597 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002599 f++;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 }
2602 precision = -1;
2603 if (*f == '.') {
2604 f++;
2605 if (Py_ISDIGIT((unsigned)*f)) {
2606 precision = (*f - '0');
2607 f++;
2608 while (Py_ISDIGIT((unsigned)*f)) {
2609 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2610 PyErr_SetString(PyExc_ValueError,
2611 "precision too big");
2612 return NULL;
2613 }
2614 precision = (precision * 10) + (*f - '0');
2615 f++;
2616 }
2617 }
Victor Stinner96865452011-03-01 23:44:09 +00002618 if (*f == '%') {
2619 /* "%.3%s" => f points to "3" */
2620 f--;
2621 }
2622 }
2623 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002624 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002625 f--;
2626 }
Victor Stinner96865452011-03-01 23:44:09 +00002627
2628 /* Handle %ld, %lu, %lld and %llu. */
2629 longflag = 0;
2630 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002631 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002632 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002633 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002634 longflag = 1;
2635 ++f;
2636 }
Victor Stinner96865452011-03-01 23:44:09 +00002637 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002639 longlongflag = 1;
2640 f += 2;
2641 }
Victor Stinner96865452011-03-01 23:44:09 +00002642 }
2643 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002644 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002645 size_tflag = 1;
2646 ++f;
2647 }
Victor Stinnere215d962012-10-06 23:03:36 +02002648
2649 if (f[1] == '\0')
2650 writer->overallocate = 0;
2651
2652 switch (*f) {
2653 case 'c':
2654 {
2655 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002656 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002657 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 "character argument not in range(0x110000)");
2659 return NULL;
2660 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002661 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002662 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002663 break;
2664 }
2665
2666 case 'i':
2667 case 'd':
2668 case 'u':
2669 case 'x':
2670 {
2671 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002672 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002673 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002674
2675 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002676 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002678 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002679 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002680 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002681 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002683 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002684 va_arg(*vargs, size_t));
2685 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, unsigned int));
2688 }
2689 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002691 }
2692 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002694 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002695 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002696 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002697 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002698 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002700 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002701 va_arg(*vargs, Py_ssize_t));
2702 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, int));
2705 }
2706 assert(len >= 0);
2707
Victor Stinnere215d962012-10-06 23:03:36 +02002708 if (precision < len)
2709 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002710
2711 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2713 return NULL;
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (width > precision) {
2716 Py_UCS4 fillchar;
2717 fill = width - precision;
2718 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002719 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2720 return NULL;
2721 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002722 }
Victor Stinner15a11362012-10-06 23:48:20 +02002723 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002724 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2726 return NULL;
2727 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002728 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002729
Victor Stinner4a587072013-11-19 12:54:53 +01002730 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2731 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002732 break;
2733 }
2734
2735 case 'p':
2736 {
2737 char number[MAX_LONG_LONG_CHARS];
2738
2739 len = sprintf(number, "%p", va_arg(*vargs, void*));
2740 assert(len >= 0);
2741
2742 /* %p is ill-defined: ensure leading 0x. */
2743 if (number[1] == 'X')
2744 number[1] = 'x';
2745 else if (number[1] != 'x') {
2746 memmove(number + 2, number,
2747 strlen(number) + 1);
2748 number[0] = '0';
2749 number[1] = 'x';
2750 len += 2;
2751 }
2752
Victor Stinner4a587072013-11-19 12:54:53 +01002753 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002754 return NULL;
2755 break;
2756 }
2757
2758 case 's':
2759 {
2760 /* UTF-8 */
2761 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002762 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002763 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002764 break;
2765 }
2766
2767 case 'U':
2768 {
2769 PyObject *obj = va_arg(*vargs, PyObject *);
2770 assert(obj && _PyUnicode_CHECK(obj));
2771
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 break;
2775 }
2776
2777 case 'V':
2778 {
2779 PyObject *obj = va_arg(*vargs, PyObject *);
2780 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002781 if (obj) {
2782 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002783 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002784 return NULL;
2785 }
2786 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002787 assert(str != NULL);
2788 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002789 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002790 }
2791 break;
2792 }
2793
2794 case 'S':
2795 {
2796 PyObject *obj = va_arg(*vargs, PyObject *);
2797 PyObject *str;
2798 assert(obj);
2799 str = PyObject_Str(obj);
2800 if (!str)
2801 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002802 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002803 Py_DECREF(str);
2804 return NULL;
2805 }
2806 Py_DECREF(str);
2807 break;
2808 }
2809
2810 case 'R':
2811 {
2812 PyObject *obj = va_arg(*vargs, PyObject *);
2813 PyObject *repr;
2814 assert(obj);
2815 repr = PyObject_Repr(obj);
2816 if (!repr)
2817 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002818 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002819 Py_DECREF(repr);
2820 return NULL;
2821 }
2822 Py_DECREF(repr);
2823 break;
2824 }
2825
2826 case 'A':
2827 {
2828 PyObject *obj = va_arg(*vargs, PyObject *);
2829 PyObject *ascii;
2830 assert(obj);
2831 ascii = PyObject_ASCII(obj);
2832 if (!ascii)
2833 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002834 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002835 Py_DECREF(ascii);
2836 return NULL;
2837 }
2838 Py_DECREF(ascii);
2839 break;
2840 }
2841
2842 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002843 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002844 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002845 break;
2846
2847 default:
2848 /* if we stumble upon an unknown formatting code, copy the rest
2849 of the format string to the output string. (we cannot just
2850 skip the code, since there's no way to know what's in the
2851 argument list) */
2852 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002853 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002854 return NULL;
2855 f = p+len;
2856 return f;
2857 }
2858
2859 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002860 return f;
2861}
2862
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863PyObject *
2864PyUnicode_FromFormatV(const char *format, va_list vargs)
2865{
Victor Stinnere215d962012-10-06 23:03:36 +02002866 va_list vargs2;
2867 const char *f;
2868 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002869
Victor Stinner8f674cc2013-04-17 23:02:17 +02002870 _PyUnicodeWriter_Init(&writer);
2871 writer.min_length = strlen(format) + 100;
2872 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002873
Benjamin Peterson0c212142016-09-20 20:39:33 -07002874 // Copy varags to be able to pass a reference to a subfunction.
2875 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002876
2877 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002878 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002879 f = unicode_fromformat_arg(&writer, f, &vargs2);
2880 if (f == NULL)
2881 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002884 const char *p;
2885 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002886
Victor Stinnere215d962012-10-06 23:03:36 +02002887 p = f;
2888 do
2889 {
2890 if ((unsigned char)*p > 127) {
2891 PyErr_Format(PyExc_ValueError,
2892 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2893 "string, got a non-ASCII byte: 0x%02x",
2894 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002895 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002896 }
2897 p++;
2898 }
2899 while (*p != '\0' && *p != '%');
2900 len = p - f;
2901
2902 if (*p == '\0')
2903 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002904
2905 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002906 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002907
2908 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002910 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002911 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002912 return _PyUnicodeWriter_Finish(&writer);
2913
2914 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002915 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002916 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918}
2919
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920PyObject *
2921PyUnicode_FromFormat(const char *format, ...)
2922{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002923 PyObject* ret;
2924 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
2926#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002927 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 ret = PyUnicode_FromFormatV(format, vargs);
2932 va_end(vargs);
2933 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002934}
2935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936#ifdef HAVE_WCHAR_H
2937
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002938/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939
Victor Stinnerd88d9832011-09-06 02:00:05 +02002940 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941 character) required to convert the unicode object. Ignore size argument.
2942
Victor Stinnerd88d9832011-09-06 02:00:05 +02002943 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002944 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002946Py_ssize_t
2947PyUnicode_AsWideChar(PyObject *unicode,
2948 wchar_t *w,
2949 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00002950{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002951 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 const wchar_t *wstr;
2953
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002954 if (unicode == NULL) {
2955 PyErr_BadInternalCall();
2956 return -1;
2957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
Victor Stinner137c34c2010-09-29 10:25:54 +00002974wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002975PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 Py_ssize_t *size)
2977{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002978 const wchar_t *wstr;
2979 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 Py_ssize_t buflen;
2981
2982 if (unicode == NULL) {
2983 PyErr_BadInternalCall();
2984 return NULL;
2985 }
2986
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002987 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
2988 if (wstr == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002989 return NULL;
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002990 }
2991 if (size == NULL && wcslen(wstr) != (size_t)buflen) {
2992 PyErr_SetString(PyExc_ValueError,
2993 "embedded null character");
2994 return NULL;
2995 }
2996
2997 buffer = PyMem_NEW(wchar_t, buflen + 1);
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 if (buffer == NULL) {
2999 PyErr_NoMemory();
3000 return NULL;
3001 }
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003002 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003003 if (size != NULL)
3004 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003005 return buffer;
3006}
3007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003008#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003012{
Victor Stinner8faf8212011-12-08 22:14:11 +01003013 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 PyErr_SetString(PyExc_ValueError,
3015 "chr() arg not in range(0x110000)");
3016 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003017 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003018
Victor Stinner985a82a2014-01-03 12:53:47 +01003019 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020}
3021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003023PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003027 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003028 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003029 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 Py_INCREF(obj);
3031 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 }
3033 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 /* For a Unicode subtype that's not a Unicode object,
3035 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003036 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003038 PyErr_Format(PyExc_TypeError,
3039 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003040 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003041 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042}
3043
Alexander Belopolsky40018472011-02-26 01:02:56 +00003044PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003045PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003046 const char *encoding,
3047 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003049 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003051
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 PyErr_BadInternalCall();
3054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 /* Decoding bytes objects is the most common case and should be fast */
3058 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003059 if (PyBytes_GET_SIZE(obj) == 0)
3060 _Py_RETURN_UNICODE_EMPTY();
3061 v = PyUnicode_Decode(
3062 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3063 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 return v;
3065 }
3066
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003067 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 PyErr_SetString(PyExc_TypeError,
3069 "decoding str is not supported");
3070 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003071 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003073 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3074 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3075 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003076 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003077 Py_TYPE(obj)->tp_name);
3078 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003079 }
Tim Petersced69f82003-09-16 20:30:58 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003082 PyBuffer_Release(&buffer);
3083 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003085
Serhiy Storchaka05997252013-01-26 12:14:02 +02003086 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003088 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089}
3090
Victor Stinnerebe17e02016-10-12 13:57:45 +02003091/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3092 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3093 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003094int
3095_Py_normalize_encoding(const char *encoding,
3096 char *lower,
3097 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003099 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003100 char *l;
3101 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003102 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003103
Victor Stinner942889a2016-09-05 15:40:10 -07003104 assert(encoding != NULL);
3105
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003106 e = encoding;
3107 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003109 punct = 0;
3110 while (1) {
3111 char c = *e;
3112 if (c == 0) {
3113 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 }
Victor Stinner942889a2016-09-05 15:40:10 -07003115
3116 if (Py_ISALNUM(c) || c == '.') {
3117 if (punct && l != lower) {
3118 if (l == l_end) {
3119 return 0;
3120 }
3121 *l++ = '_';
3122 }
3123 punct = 0;
3124
3125 if (l == l_end) {
3126 return 0;
3127 }
3128 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003129 }
3130 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003131 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003132 }
Victor Stinner942889a2016-09-05 15:40:10 -07003133
3134 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003137 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003138}
3139
Alexander Belopolsky40018472011-02-26 01:02:56 +00003140PyObject *
3141PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003142 Py_ssize_t size,
3143 const char *encoding,
3144 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003145{
3146 PyObject *buffer = NULL, *unicode;
3147 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003148 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3149
3150 if (encoding == NULL) {
3151 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3152 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003153
Fred Drakee4315f52000-05-09 19:53:39 +00003154 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003155 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3156 char *lower = buflower;
3157
3158 /* Fast paths */
3159 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3160 lower += 3;
3161 if (*lower == '_') {
3162 /* Match "utf8" and "utf_8" */
3163 lower++;
3164 }
3165
3166 if (lower[0] == '8' && lower[1] == 0) {
3167 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3168 }
3169 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3170 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3171 }
3172 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3173 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3174 }
3175 }
3176 else {
3177 if (strcmp(lower, "ascii") == 0
3178 || strcmp(lower, "us_ascii") == 0) {
3179 return PyUnicode_DecodeASCII(s, size, errors);
3180 }
Steve Dowercc16be82016-09-08 10:35:16 -07003181 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003182 else if (strcmp(lower, "mbcs") == 0) {
3183 return PyUnicode_DecodeMBCS(s, size, errors);
3184 }
3185 #endif
3186 else if (strcmp(lower, "latin1") == 0
3187 || strcmp(lower, "latin_1") == 0
3188 || strcmp(lower, "iso_8859_1") == 0
3189 || strcmp(lower, "iso8859_1") == 0) {
3190 return PyUnicode_DecodeLatin1(s, size, errors);
3191 }
3192 }
Victor Stinner37296e82010-06-10 13:36:23 +00003193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003194
3195 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003196 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003197 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003198 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003199 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200 if (buffer == NULL)
3201 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003202 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 if (unicode == NULL)
3204 goto onError;
3205 if (!PyUnicode_Check(unicode)) {
3206 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003207 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3208 "use codecs.decode() to decode to arbitrary types",
3209 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003210 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 Py_DECREF(unicode);
3212 goto onError;
3213 }
3214 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003215 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003216
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 Py_XDECREF(buffer);
3219 return NULL;
3220}
3221
Alexander Belopolsky40018472011-02-26 01:02:56 +00003222PyObject *
3223PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003224 const char *encoding,
3225 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003226{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003229 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003230 }
3231
Serhiy Storchaka00939072016-10-27 21:05:49 +03003232 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3233 "PyUnicode_AsDecodedObject() is deprecated; "
3234 "use PyCodec_Decode() to decode from str", 1) < 0)
3235 return NULL;
3236
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003237 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003239
3240 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003241 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242}
3243
Alexander Belopolsky40018472011-02-26 01:02:56 +00003244PyObject *
3245PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003246 const char *encoding,
3247 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003248{
3249 PyObject *v;
3250
3251 if (!PyUnicode_Check(unicode)) {
3252 PyErr_BadArgument();
3253 goto onError;
3254 }
3255
Serhiy Storchaka00939072016-10-27 21:05:49 +03003256 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3257 "PyUnicode_AsDecodedUnicode() is deprecated; "
3258 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3259 return NULL;
3260
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003261 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003262 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003263
3264 /* Decode via the codec registry */
3265 v = PyCodec_Decode(unicode, encoding, errors);
3266 if (v == NULL)
3267 goto onError;
3268 if (!PyUnicode_Check(v)) {
3269 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003270 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3271 "use codecs.decode() to decode to arbitrary types",
3272 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003273 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003274 Py_DECREF(v);
3275 goto onError;
3276 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003277 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003280 return NULL;
3281}
3282
Alexander Belopolsky40018472011-02-26 01:02:56 +00003283PyObject *
3284PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003285 Py_ssize_t size,
3286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003290
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003291 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3295 Py_DECREF(unicode);
3296 return v;
3297}
3298
Alexander Belopolsky40018472011-02-26 01:02:56 +00003299PyObject *
3300PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003301 const char *encoding,
3302 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003303{
3304 PyObject *v;
3305
3306 if (!PyUnicode_Check(unicode)) {
3307 PyErr_BadArgument();
3308 goto onError;
3309 }
3310
Serhiy Storchaka00939072016-10-27 21:05:49 +03003311 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3312 "PyUnicode_AsEncodedObject() is deprecated; "
3313 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3314 "or PyCodec_Encode() for generic encoding", 1) < 0)
3315 return NULL;
3316
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003318 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003319
3320 /* Encode via the codec registry */
3321 v = PyCodec_Encode(unicode, encoding, errors);
3322 if (v == NULL)
3323 goto onError;
3324 return v;
3325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327 return NULL;
3328}
3329
Victor Stinner1b579672011-12-17 05:47:23 +01003330static int
3331locale_error_handler(const char *errors, int *surrogateescape)
3332{
Victor Stinner50149202015-09-22 00:26:54 +02003333 _Py_error_handler error_handler = get_error_handler(errors);
3334 switch (error_handler)
3335 {
3336 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003337 *surrogateescape = 0;
3338 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003339 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003340 *surrogateescape = 1;
3341 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003342 default:
3343 PyErr_Format(PyExc_ValueError,
3344 "only 'strict' and 'surrogateescape' error handlers "
3345 "are supported, not '%s'",
3346 errors);
3347 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003348 }
Victor Stinner1b579672011-12-17 05:47:23 +01003349}
3350
Victor Stinner2cba6b82018-01-10 22:46:15 +01003351static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003352unicode_encode_locale(PyObject *unicode, const char *errors,
3353 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003354{
Victor Stinner1b579672011-12-17 05:47:23 +01003355 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003356 if (locale_error_handler(errors, &surrogateescape) < 0)
3357 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003358
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003359 Py_ssize_t wlen;
3360 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3361 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003362 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003363 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003364
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003365 Py_ssize_t wlen2 = wcslen(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003366 if (wlen2 != wlen) {
3367 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003368 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 return NULL;
3370 }
3371
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003372 char *str;
3373 size_t error_pos;
3374 const char *reason;
3375 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3376 current_locale, surrogateescape);
3377 if (res != 0) {
3378 if (res == -2) {
3379 PyObject *exc;
3380 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3381 "locale", unicode,
3382 (Py_ssize_t)error_pos,
3383 (Py_ssize_t)(error_pos+1),
3384 reason);
3385 if (exc != NULL) {
3386 PyCodec_StrictErrors(exc);
3387 Py_DECREF(exc);
3388 }
3389 return NULL;
Victor Stinner2cba6b82018-01-10 22:46:15 +01003390 }
3391 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003392 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003393 PyMem_Free(wstr);
3394 return NULL;
3395 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003397 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003399 PyObject *bytes = PyBytes_FromString(str);
3400 PyMem_RawFree(str);
3401 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003402}
3403
Victor Stinnerad158722010-10-27 00:25:46 +00003404PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003405PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3406{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003407 return unicode_encode_locale(unicode, errors, 1);
3408}
3409
3410PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003411PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003412{
Steve Dowercc16be82016-09-08 10:35:16 -07003413#if defined(__APPLE__)
3414 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003415#else
Victor Stinner793b5312011-04-27 00:24:21 +02003416 PyInterpreterState *interp = PyThreadState_GET()->interp;
3417 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3418 cannot use it to encode and decode filenames before it is loaded. Load
3419 the Python codec requires to encode at least its own filename. Use the C
3420 version of the locale codec until the codec registry is initialized and
3421 the Python codec is loaded.
3422
3423 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3424 cannot only rely on it: check also interp->fscodec_initialized for
3425 subinterpreters. */
3426 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003427 return PyUnicode_AsEncodedString(unicode,
3428 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003429 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003430 }
3431 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003432 return unicode_encode_locale(unicode,
3433 Py_FileSystemDefaultEncodeErrors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003434 }
Victor Stinnerad158722010-10-27 00:25:46 +00003435#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003436}
3437
Alexander Belopolsky40018472011-02-26 01:02:56 +00003438PyObject *
3439PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003440 const char *encoding,
3441 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003442{
3443 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003444 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003445
Guido van Rossumd57fd912000-03-10 22:53:23 +00003446 if (!PyUnicode_Check(unicode)) {
3447 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003448 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449 }
Fred Drakee4315f52000-05-09 19:53:39 +00003450
Victor Stinner942889a2016-09-05 15:40:10 -07003451 if (encoding == NULL) {
3452 return _PyUnicode_AsUTF8String(unicode, errors);
3453 }
3454
Fred Drakee4315f52000-05-09 19:53:39 +00003455 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003456 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3457 char *lower = buflower;
3458
3459 /* Fast paths */
3460 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3461 lower += 3;
3462 if (*lower == '_') {
3463 /* Match "utf8" and "utf_8" */
3464 lower++;
3465 }
3466
3467 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003468 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003469 }
3470 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3471 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3472 }
3473 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3474 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3475 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003476 }
Victor Stinner942889a2016-09-05 15:40:10 -07003477 else {
3478 if (strcmp(lower, "ascii") == 0
3479 || strcmp(lower, "us_ascii") == 0) {
3480 return _PyUnicode_AsASCIIString(unicode, errors);
3481 }
Steve Dowercc16be82016-09-08 10:35:16 -07003482#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003483 else if (strcmp(lower, "mbcs") == 0) {
3484 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3485 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003486#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003487 else if (strcmp(lower, "latin1") == 0 ||
3488 strcmp(lower, "latin_1") == 0 ||
3489 strcmp(lower, "iso_8859_1") == 0 ||
3490 strcmp(lower, "iso8859_1") == 0) {
3491 return _PyUnicode_AsLatin1String(unicode, errors);
3492 }
3493 }
Victor Stinner37296e82010-06-10 13:36:23 +00003494 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003495
3496 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003497 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003499 return NULL;
3500
3501 /* The normal path */
3502 if (PyBytes_Check(v))
3503 return v;
3504
3505 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003506 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003507 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003508 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003509
3510 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003511 "encoder %s returned bytearray instead of bytes; "
3512 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003513 encoding);
3514 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003515 Py_DECREF(v);
3516 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003517 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003518
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003519 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3520 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003521 Py_DECREF(v);
3522 return b;
3523 }
3524
3525 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003526 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3527 "use codecs.encode() to encode to arbitrary types",
3528 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003529 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003530 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003531 return NULL;
3532}
3533
Alexander Belopolsky40018472011-02-26 01:02:56 +00003534PyObject *
3535PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003536 const char *encoding,
3537 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003538{
3539 PyObject *v;
3540
3541 if (!PyUnicode_Check(unicode)) {
3542 PyErr_BadArgument();
3543 goto onError;
3544 }
3545
Serhiy Storchaka00939072016-10-27 21:05:49 +03003546 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3547 "PyUnicode_AsEncodedUnicode() is deprecated; "
3548 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3549 return NULL;
3550
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003551 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003552 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003553
3554 /* Encode via the codec registry */
3555 v = PyCodec_Encode(unicode, encoding, errors);
3556 if (v == NULL)
3557 goto onError;
3558 if (!PyUnicode_Check(v)) {
3559 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003560 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3561 "use codecs.encode() to encode to arbitrary types",
3562 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003563 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003564 Py_DECREF(v);
3565 goto onError;
3566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003567 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003568
Benjamin Peterson29060642009-01-31 22:14:21 +00003569 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003570 return NULL;
3571}
3572
Victor Stinner2cba6b82018-01-10 22:46:15 +01003573static PyObject*
3574unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3575 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003576{
Victor Stinner1b579672011-12-17 05:47:23 +01003577 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003578 if (locale_error_handler(errors, &surrogateescape) < 0)
3579 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003580
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003581 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3582 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003583 return NULL;
3584 }
3585
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003586 wchar_t *wstr;
3587 size_t wlen;
3588 const char *reason;
3589 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3590 current_locale, surrogateescape);
3591 if (res != 0) {
3592 if (res == -2) {
3593 PyObject *exc;
3594 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3595 "locale", str, len,
3596 (Py_ssize_t)wlen,
3597 (Py_ssize_t)(wlen + 1),
3598 reason);
3599 if (exc != NULL) {
3600 PyCodec_StrictErrors(exc);
3601 Py_DECREF(exc);
3602 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003603 }
3604 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003605 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003606 }
Victor Stinner2f197072011-12-17 07:08:30 +01003607 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003608 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003609
3610 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3611 PyMem_RawFree(wstr);
3612 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003613}
3614
3615PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003616PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3617 const char *errors)
3618{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003619 return unicode_decode_locale(str, len, errors, 1);
3620}
3621
3622PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003623PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003624{
3625 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003626 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003627}
3628
3629
3630PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003631PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003632 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003633 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3634}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003635
Christian Heimes5894ba72007-11-04 11:43:14 +00003636PyObject*
3637PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3638{
Steve Dowercc16be82016-09-08 10:35:16 -07003639#if defined(__APPLE__)
3640 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003641#else
Victor Stinner793b5312011-04-27 00:24:21 +02003642 PyInterpreterState *interp = PyThreadState_GET()->interp;
3643 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3644 cannot use it to encode and decode filenames before it is loaded. Load
3645 the Python codec requires to encode at least its own filename. Use the C
3646 version of the locale codec until the codec registry is initialized and
3647 the Python codec is loaded.
3648
3649 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3650 cannot only rely on it: check also interp->fscodec_initialized for
3651 subinterpreters. */
3652 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003653 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003654 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003655 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003656 }
3657 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003658 return unicode_decode_locale(s, size,
3659 Py_FileSystemDefaultEncodeErrors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003660 }
Victor Stinnerad158722010-10-27 00:25:46 +00003661#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003662}
3663
Martin v. Löwis011e8422009-05-05 04:43:17 +00003664
3665int
3666PyUnicode_FSConverter(PyObject* arg, void* addr)
3667{
Brett Cannonec6ce872016-09-06 15:50:29 -07003668 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003669 PyObject *output = NULL;
3670 Py_ssize_t size;
3671 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003672 if (arg == NULL) {
3673 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003674 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 return 1;
3676 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003677 path = PyOS_FSPath(arg);
3678 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003679 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003680 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003681 if (PyBytes_Check(path)) {
3682 output = path;
3683 }
3684 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3685 output = PyUnicode_EncodeFSDefault(path);
3686 Py_DECREF(path);
3687 if (!output) {
3688 return 0;
3689 }
3690 assert(PyBytes_Check(output));
3691 }
3692
Victor Stinner0ea2a462010-04-30 00:22:08 +00003693 size = PyBytes_GET_SIZE(output);
3694 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003695 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003696 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003697 Py_DECREF(output);
3698 return 0;
3699 }
3700 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003701 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003702}
3703
3704
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003705int
3706PyUnicode_FSDecoder(PyObject* arg, void* addr)
3707{
Brett Cannona5711202016-09-06 19:36:01 -07003708 int is_buffer = 0;
3709 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003710 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003711 if (arg == NULL) {
3712 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003713 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003714 return 1;
3715 }
Brett Cannona5711202016-09-06 19:36:01 -07003716
3717 is_buffer = PyObject_CheckBuffer(arg);
3718 if (!is_buffer) {
3719 path = PyOS_FSPath(arg);
3720 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003721 return 0;
3722 }
Brett Cannona5711202016-09-06 19:36:01 -07003723 }
3724 else {
3725 path = arg;
3726 Py_INCREF(arg);
3727 }
3728
3729 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003730 output = path;
3731 }
3732 else if (PyBytes_Check(path) || is_buffer) {
3733 PyObject *path_bytes = NULL;
3734
3735 if (!PyBytes_Check(path) &&
3736 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3737 "path should be string, bytes, or os.PathLike, not %.200s",
3738 Py_TYPE(arg)->tp_name)) {
3739 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003740 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003741 }
3742 path_bytes = PyBytes_FromObject(path);
3743 Py_DECREF(path);
3744 if (!path_bytes) {
3745 return 0;
3746 }
3747 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3748 PyBytes_GET_SIZE(path_bytes));
3749 Py_DECREF(path_bytes);
3750 if (!output) {
3751 return 0;
3752 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003753 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003754 else {
3755 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003756 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003757 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003758 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003759 return 0;
3760 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003761 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003762 Py_DECREF(output);
3763 return 0;
3764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003765 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003766 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003767 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003768 Py_DECREF(output);
3769 return 0;
3770 }
3771 *(PyObject**)addr = output;
3772 return Py_CLEANUP_SUPPORTED;
3773}
3774
3775
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003776const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003778{
Christian Heimesf3863112007-11-22 07:46:41 +00003779 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003781 if (!PyUnicode_Check(unicode)) {
3782 PyErr_BadArgument();
3783 return NULL;
3784 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003785 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003786 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003787
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003788 if (PyUnicode_UTF8(unicode) == NULL) {
3789 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003790 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 if (bytes == NULL)
3792 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003793 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3794 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003795 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796 Py_DECREF(bytes);
3797 return NULL;
3798 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003799 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003800 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003801 PyBytes_AS_STRING(bytes),
3802 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003803 Py_DECREF(bytes);
3804 }
3805
3806 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003807 *psize = PyUnicode_UTF8_LENGTH(unicode);
3808 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003809}
3810
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003811const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003814 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3815}
3816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817Py_UNICODE *
3818PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3819{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 const unsigned char *one_byte;
3821#if SIZEOF_WCHAR_T == 4
3822 const Py_UCS2 *two_bytes;
3823#else
3824 const Py_UCS4 *four_bytes;
3825 const Py_UCS4 *ucs4_end;
3826 Py_ssize_t num_surrogates;
3827#endif
3828 wchar_t *w;
3829 wchar_t *wchar_end;
3830
3831 if (!PyUnicode_Check(unicode)) {
3832 PyErr_BadArgument();
3833 return NULL;
3834 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003837 assert(_PyUnicode_KIND(unicode) != 0);
3838 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3843 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 num_surrogates = 0;
3845
3846 for (; four_bytes < ucs4_end; ++four_bytes) {
3847 if (*four_bytes > 0xFFFF)
3848 ++num_surrogates;
3849 }
3850
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003851 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3852 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3853 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854 PyErr_NoMemory();
3855 return NULL;
3856 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003857 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003859 w = _PyUnicode_WSTR(unicode);
3860 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3861 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3863 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003864 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003866 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3867 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 }
3869 else
3870 *w = *four_bytes;
3871
3872 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07003873 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 }
3875 }
3876 *w = 0;
3877#else
3878 /* sizeof(wchar_t) == 4 */
3879 Py_FatalError("Impossible unicode object state, wstr and str "
3880 "should share memory already.");
3881 return NULL;
3882#endif
3883 }
3884 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003885 if ((size_t)_PyUnicode_LENGTH(unicode) >
3886 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3887 PyErr_NoMemory();
3888 return NULL;
3889 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003890 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3891 (_PyUnicode_LENGTH(unicode) + 1));
3892 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 PyErr_NoMemory();
3894 return NULL;
3895 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003896 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3897 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3898 w = _PyUnicode_WSTR(unicode);
3899 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003900
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003901 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3902 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003903 for (; w < wchar_end; ++one_byte, ++w)
3904 *w = *one_byte;
3905 /* null-terminate the wstr */
3906 *w = 0;
3907 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003908 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003910 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911 for (; w < wchar_end; ++two_bytes, ++w)
3912 *w = *two_bytes;
3913 /* null-terminate the wstr */
3914 *w = 0;
3915#else
3916 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003917 PyObject_FREE(_PyUnicode_WSTR(unicode));
3918 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003919 Py_FatalError("Impossible unicode object state, wstr "
3920 "and str should share memory already.");
3921 return NULL;
3922#endif
3923 }
3924 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07003925 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 }
3927 }
3928 }
3929 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003930 *size = PyUnicode_WSTR_LENGTH(unicode);
3931 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003932}
3933
Alexander Belopolsky40018472011-02-26 01:02:56 +00003934Py_UNICODE *
3935PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003936{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003938}
3939
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003940const Py_UNICODE *
3941_PyUnicode_AsUnicode(PyObject *unicode)
3942{
3943 Py_ssize_t size;
3944 const Py_UNICODE *wstr;
3945
3946 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3947 if (wstr && wcslen(wstr) != (size_t)size) {
3948 PyErr_SetString(PyExc_ValueError, "embedded null character");
3949 return NULL;
3950 }
3951 return wstr;
3952}
3953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954
Alexander Belopolsky40018472011-02-26 01:02:56 +00003955Py_ssize_t
3956PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003957{
3958 if (!PyUnicode_Check(unicode)) {
3959 PyErr_BadArgument();
3960 goto onError;
3961 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003962 if (_PyUnicode_WSTR(unicode) == NULL) {
3963 if (PyUnicode_AsUnicode(unicode) == NULL)
3964 goto onError;
3965 }
3966 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003967
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003969 return -1;
3970}
3971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972Py_ssize_t
3973PyUnicode_GetLength(PyObject *unicode)
3974{
Victor Stinner07621332012-06-16 04:53:46 +02003975 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976 PyErr_BadArgument();
3977 return -1;
3978 }
Victor Stinner07621332012-06-16 04:53:46 +02003979 if (PyUnicode_READY(unicode) == -1)
3980 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 return PyUnicode_GET_LENGTH(unicode);
3982}
3983
3984Py_UCS4
3985PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3986{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003987 void *data;
3988 int kind;
3989
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003990 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003991 PyErr_BadArgument();
3992 return (Py_UCS4)-1;
3993 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003994 if (PyUnicode_READY(unicode) == -1) {
3995 return (Py_UCS4)-1;
3996 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003997 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003998 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 return (Py_UCS4)-1;
4000 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004001 data = PyUnicode_DATA(unicode);
4002 kind = PyUnicode_KIND(unicode);
4003 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004}
4005
4006int
4007PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4008{
4009 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004010 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 return -1;
4012 }
Victor Stinner488fa492011-12-12 00:01:39 +01004013 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004014 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004015 PyErr_SetString(PyExc_IndexError, "string index out of range");
4016 return -1;
4017 }
Victor Stinner488fa492011-12-12 00:01:39 +01004018 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004019 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004020 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4021 PyErr_SetString(PyExc_ValueError, "character out of range");
4022 return -1;
4023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4025 index, ch);
4026 return 0;
4027}
4028
Alexander Belopolsky40018472011-02-26 01:02:56 +00004029const char *
4030PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004031{
Victor Stinner42cb4622010-09-01 19:39:01 +00004032 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004033}
4034
Victor Stinner554f3f02010-06-16 23:33:54 +00004035/* create or adjust a UnicodeDecodeError */
4036static void
4037make_decode_exception(PyObject **exceptionObject,
4038 const char *encoding,
4039 const char *input, Py_ssize_t length,
4040 Py_ssize_t startpos, Py_ssize_t endpos,
4041 const char *reason)
4042{
4043 if (*exceptionObject == NULL) {
4044 *exceptionObject = PyUnicodeDecodeError_Create(
4045 encoding, input, length, startpos, endpos, reason);
4046 }
4047 else {
4048 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4049 goto onError;
4050 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4051 goto onError;
4052 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4053 goto onError;
4054 }
4055 return;
4056
4057onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004058 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004059}
4060
Steve Dowercc16be82016-09-08 10:35:16 -07004061#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062/* error handling callback helper:
4063 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004064 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004065 and adjust various state variables.
4066 return 0 on success, -1 on error
4067*/
4068
Alexander Belopolsky40018472011-02-26 01:02:56 +00004069static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004070unicode_decode_call_errorhandler_wchar(
4071 const char *errors, PyObject **errorHandler,
4072 const char *encoding, const char *reason,
4073 const char **input, const char **inend, Py_ssize_t *startinpos,
4074 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4075 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004077 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078
4079 PyObject *restuple = NULL;
4080 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004081 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004082 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004083 Py_ssize_t requiredsize;
4084 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004085 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 wchar_t *repwstr;
4087 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004088
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004089 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4090 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004091
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004093 *errorHandler = PyCodec_LookupError(errors);
4094 if (*errorHandler == NULL)
4095 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004096 }
4097
Victor Stinner554f3f02010-06-16 23:33:54 +00004098 make_decode_exception(exceptionObject,
4099 encoding,
4100 *input, *inend - *input,
4101 *startinpos, *endinpos,
4102 reason);
4103 if (*exceptionObject == NULL)
4104 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004105
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004106 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004108 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004109 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004110 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004112 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004113 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004114 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004115
4116 /* Copy back the bytes variables, which might have been modified by the
4117 callback */
4118 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4119 if (!inputobj)
4120 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004121 *input = PyBytes_AS_STRING(inputobj);
4122 insize = PyBytes_GET_SIZE(inputobj);
4123 *inend = *input + insize;
4124 /* we can DECREF safely, as the exception has another reference,
4125 so the object won't go away. */
4126 Py_DECREF(inputobj);
4127
4128 if (newpos<0)
4129 newpos = insize+newpos;
4130 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004131 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004132 goto onError;
4133 }
4134
4135 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4136 if (repwstr == NULL)
4137 goto onError;
4138 /* need more space? (at least enough for what we
4139 have+the replacement+the rest of the string (starting
4140 at the new input position), so we won't have to check space
4141 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004142 requiredsize = *outpos;
4143 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4144 goto overflow;
4145 requiredsize += repwlen;
4146 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4147 goto overflow;
4148 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004149 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004150 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004151 requiredsize = 2*outsize;
4152 if (unicode_resize(output, requiredsize) < 0)
4153 goto onError;
4154 }
4155 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4156 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004157 *endinpos = newpos;
4158 *inptr = *input + newpos;
4159
4160 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004161 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004162 return 0;
4163
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004164 overflow:
4165 PyErr_SetString(PyExc_OverflowError,
4166 "decoded result is too long for a Python string");
4167
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004168 onError:
4169 Py_XDECREF(restuple);
4170 return -1;
4171}
Steve Dowercc16be82016-09-08 10:35:16 -07004172#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004173
4174static int
4175unicode_decode_call_errorhandler_writer(
4176 const char *errors, PyObject **errorHandler,
4177 const char *encoding, const char *reason,
4178 const char **input, const char **inend, Py_ssize_t *startinpos,
4179 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4180 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4181{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004182 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004183
4184 PyObject *restuple = NULL;
4185 PyObject *repunicode = NULL;
4186 Py_ssize_t insize;
4187 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004188 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004189 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004191 int need_to_grow = 0;
4192 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004193
4194 if (*errorHandler == NULL) {
4195 *errorHandler = PyCodec_LookupError(errors);
4196 if (*errorHandler == NULL)
4197 goto onError;
4198 }
4199
4200 make_decode_exception(exceptionObject,
4201 encoding,
4202 *input, *inend - *input,
4203 *startinpos, *endinpos,
4204 reason);
4205 if (*exceptionObject == NULL)
4206 goto onError;
4207
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004208 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004209 if (restuple == NULL)
4210 goto onError;
4211 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004212 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004213 goto onError;
4214 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004215 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004216 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004217
4218 /* Copy back the bytes variables, which might have been modified by the
4219 callback */
4220 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4221 if (!inputobj)
4222 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004223 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004224 *input = PyBytes_AS_STRING(inputobj);
4225 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004226 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004227 /* we can DECREF safely, as the exception has another reference,
4228 so the object won't go away. */
4229 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004230
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004232 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004233 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004234 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004235 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004236 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237
Victor Stinner170ca6f2013-04-18 00:25:28 +02004238 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004239 if (replen > 1) {
4240 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004241 need_to_grow = 1;
4242 }
4243 new_inptr = *input + newpos;
4244 if (*inend - new_inptr > remain) {
4245 /* We don't know the decoding algorithm here so we make the worst
4246 assumption that one byte decodes to one unicode character.
4247 If unfortunately one byte could decode to more unicode characters,
4248 the decoder may write out-of-bound then. Is it possible for the
4249 algorithms using this function? */
4250 writer->min_length += *inend - new_inptr - remain;
4251 need_to_grow = 1;
4252 }
4253 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004254 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004255 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004256 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4257 goto onError;
4258 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004259 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004260 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004261
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004263 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004264
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004265 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004266 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004267 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268
Benjamin Peterson29060642009-01-31 22:14:21 +00004269 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004271 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272}
4273
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274/* --- UTF-7 Codec -------------------------------------------------------- */
4275
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276/* See RFC2152 for details. We encode conservatively and decode liberally. */
4277
4278/* Three simple macros defining base-64. */
4279
4280/* Is c a base-64 character? */
4281
4282#define IS_BASE64(c) \
4283 (((c) >= 'A' && (c) <= 'Z') || \
4284 ((c) >= 'a' && (c) <= 'z') || \
4285 ((c) >= '0' && (c) <= '9') || \
4286 (c) == '+' || (c) == '/')
4287
4288/* given that c is a base-64 character, what is its base-64 value? */
4289
4290#define FROM_BASE64(c) \
4291 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4292 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4293 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4294 (c) == '+' ? 62 : 63)
4295
4296/* What is the base-64 character of the bottom 6 bits of n? */
4297
4298#define TO_BASE64(n) \
4299 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4300
4301/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4302 * decoded as itself. We are permissive on decoding; the only ASCII
4303 * byte not decoding to itself is the + which begins a base64
4304 * string. */
4305
4306#define DECODE_DIRECT(c) \
4307 ((c) <= 127 && (c) != '+')
4308
4309/* The UTF-7 encoder treats ASCII characters differently according to
4310 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4311 * the above). See RFC2152. This array identifies these different
4312 * sets:
4313 * 0 : "Set D"
4314 * alphanumeric and '(),-./:?
4315 * 1 : "Set O"
4316 * !"#$%&*;<=>@[]^_`{|}
4317 * 2 : "whitespace"
4318 * ht nl cr sp
4319 * 3 : special (must be base64 encoded)
4320 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4321 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322
Tim Petersced69f82003-09-16 20:30:58 +00004323static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324char utf7_category[128] = {
4325/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4326 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4327/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4328 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4329/* sp ! " # $ % & ' ( ) * + , - . / */
4330 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4331/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4332 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4333/* @ A B C D E F G H I J K L M N O */
4334 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4335/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4336 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4337/* ` a b c d e f g h i j k l m n o */
4338 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4339/* p q r s t u v w x y z { | } ~ del */
4340 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341};
4342
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343/* ENCODE_DIRECT: this character should be encoded as itself. The
4344 * answer depends on whether we are encoding set O as itself, and also
4345 * on whether we are encoding whitespace as itself. RFC2152 makes it
4346 * clear that the answers to these questions vary between
4347 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004348
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349#define ENCODE_DIRECT(c, directO, directWS) \
4350 ((c) < 128 && (c) > 0 && \
4351 ((utf7_category[(c)] == 0) || \
4352 (directWS && (utf7_category[(c)] == 2)) || \
4353 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004354
Alexander Belopolsky40018472011-02-26 01:02:56 +00004355PyObject *
4356PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004357 Py_ssize_t size,
4358 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004360 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4361}
4362
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363/* The decoder. The only state we preserve is our read position,
4364 * i.e. how many characters we have consumed. So if we end in the
4365 * middle of a shift sequence we have to back off the read position
4366 * and the output to the beginning of the sequence, otherwise we lose
4367 * all the shift state (seen bits, number of bits seen, high
4368 * surrogate). */
4369
Alexander Belopolsky40018472011-02-26 01:02:56 +00004370PyObject *
4371PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004372 Py_ssize_t size,
4373 const char *errors,
4374 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004375{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004376 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004377 Py_ssize_t startinpos;
4378 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004379 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004380 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 const char *errmsg = "";
4382 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004383 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004384 unsigned int base64bits = 0;
4385 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004386 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004387 PyObject *errorHandler = NULL;
4388 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004390 if (size == 0) {
4391 if (consumed)
4392 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004393 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004394 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004396 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004397 _PyUnicodeWriter_Init(&writer);
4398 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004399
4400 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 e = s + size;
4402
4403 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004404 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004406 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 if (inShift) { /* in a base-64 section */
4409 if (IS_BASE64(ch)) { /* consume a base-64 character */
4410 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4411 base64bits += 6;
4412 s++;
4413 if (base64bits >= 16) {
4414 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004415 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 base64bits -= 16;
4417 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004418 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 if (surrogate) {
4420 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004421 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4422 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004423 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004424 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004426 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 }
4428 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004429 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004430 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 }
4433 }
Victor Stinner551ac952011-11-29 22:58:13 +01004434 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004435 /* first surrogate */
4436 surrogate = outCh;
4437 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004439 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004440 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 }
4442 }
4443 }
4444 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 if (base64bits > 0) { /* left-over bits */
4447 if (base64bits >= 6) {
4448 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004449 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 errmsg = "partial character in shift sequence";
4451 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 else {
4454 /* Some bits remain; they should be zero */
4455 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004456 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 errmsg = "non-zero padding bits in shift sequence";
4458 goto utf7Error;
4459 }
4460 }
4461 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004462 if (surrogate && DECODE_DIRECT(ch)) {
4463 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4464 goto onError;
4465 }
4466 surrogate = 0;
4467 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 /* '-' is absorbed; other terminating
4469 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004470 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 }
4473 }
4474 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004475 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 s++; /* consume '+' */
4477 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004479 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004480 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 }
4482 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004484 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004485 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004487 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488 }
4489 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004491 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004492 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004493 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 else {
4496 startinpos = s-starts;
4497 s++;
4498 errmsg = "unexpected special character";
4499 goto utf7Error;
4500 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004501 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004503 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004504 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004505 errors, &errorHandler,
4506 "utf7", errmsg,
4507 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004508 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004510 }
4511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 /* end of string */
4513
4514 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4515 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004516 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 if (surrogate ||
4518 (base64bits >= 6) ||
4519 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004521 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 errors, &errorHandler,
4523 "utf7", "unterminated shift sequence",
4524 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004525 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 goto onError;
4527 if (s < e)
4528 goto restart;
4529 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531
4532 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004533 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004535 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004536 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004537 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004538 writer.kind, writer.data, shiftOutStart);
4539 Py_XDECREF(errorHandler);
4540 Py_XDECREF(exc);
4541 _PyUnicodeWriter_Dealloc(&writer);
4542 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004543 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004544 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 }
4546 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004547 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004548 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004549 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004551 Py_XDECREF(errorHandler);
4552 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004553 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554
Benjamin Peterson29060642009-01-31 22:14:21 +00004555 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004556 Py_XDECREF(errorHandler);
4557 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559 return NULL;
4560}
4561
4562
Alexander Belopolsky40018472011-02-26 01:02:56 +00004563PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004564_PyUnicode_EncodeUTF7(PyObject *str,
4565 int base64SetO,
4566 int base64WhiteSpace,
4567 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004568{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004569 int kind;
4570 void *data;
4571 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004572 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004573 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004574 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 unsigned int base64bits = 0;
4576 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004577 char * out;
4578 char * start;
4579
Benjamin Petersonbac79492012-01-14 13:34:47 -05004580 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004581 return NULL;
4582 kind = PyUnicode_KIND(str);
4583 data = PyUnicode_DATA(str);
4584 len = PyUnicode_GET_LENGTH(str);
4585
4586 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004587 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004589 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004590 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004591 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004592 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004593 if (v == NULL)
4594 return NULL;
4595
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004596 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004597 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004598 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004599
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600 if (inShift) {
4601 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4602 /* shifting out */
4603 if (base64bits) { /* output remaining bits */
4604 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4605 base64buffer = 0;
4606 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004607 }
4608 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004609 /* Characters not in the BASE64 set implicitly unshift the sequence
4610 so no '-' is required, except if the character is itself a '-' */
4611 if (IS_BASE64(ch) || ch == '-') {
4612 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 *out++ = (char) ch;
4615 }
4616 else {
4617 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004618 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004619 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004620 else { /* not in a shift sequence */
4621 if (ch == '+') {
4622 *out++ = '+';
4623 *out++ = '-';
4624 }
4625 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4626 *out++ = (char) ch;
4627 }
4628 else {
4629 *out++ = '+';
4630 inShift = 1;
4631 goto encode_char;
4632 }
4633 }
4634 continue;
4635encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004637 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004638
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 /* code first surrogate */
4640 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004641 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004642 while (base64bits >= 6) {
4643 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4644 base64bits -= 6;
4645 }
4646 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004647 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004648 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004649 base64bits += 16;
4650 base64buffer = (base64buffer << 16) | ch;
4651 while (base64bits >= 6) {
4652 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4653 base64bits -= 6;
4654 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004655 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004656 if (base64bits)
4657 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4658 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004660 if (_PyBytes_Resize(&v, out - start) < 0)
4661 return NULL;
4662 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004663}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004664PyObject *
4665PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4666 Py_ssize_t size,
4667 int base64SetO,
4668 int base64WhiteSpace,
4669 const char *errors)
4670{
4671 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004672 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004673 if (tmp == NULL)
4674 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004675 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004676 base64WhiteSpace, errors);
4677 Py_DECREF(tmp);
4678 return result;
4679}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004680
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681#undef IS_BASE64
4682#undef FROM_BASE64
4683#undef TO_BASE64
4684#undef DECODE_DIRECT
4685#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004686
Guido van Rossumd57fd912000-03-10 22:53:23 +00004687/* --- UTF-8 Codec -------------------------------------------------------- */
4688
Alexander Belopolsky40018472011-02-26 01:02:56 +00004689PyObject *
4690PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004691 Py_ssize_t size,
4692 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004693{
Walter Dörwald69652032004-09-07 20:24:22 +00004694 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4695}
4696
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004697#include "stringlib/asciilib.h"
4698#include "stringlib/codecs.h"
4699#include "stringlib/undef.h"
4700
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004701#include "stringlib/ucs1lib.h"
4702#include "stringlib/codecs.h"
4703#include "stringlib/undef.h"
4704
4705#include "stringlib/ucs2lib.h"
4706#include "stringlib/codecs.h"
4707#include "stringlib/undef.h"
4708
4709#include "stringlib/ucs4lib.h"
4710#include "stringlib/codecs.h"
4711#include "stringlib/undef.h"
4712
Antoine Pitrouab868312009-01-10 15:40:25 +00004713/* Mask to quickly check whether a C 'long' contains a
4714 non-ASCII, UTF8-encoded char. */
4715#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004716# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004717#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004718# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004719#else
4720# error C 'long' size should be either 4 or 8!
4721#endif
4722
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723static Py_ssize_t
4724ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004725{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004727 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004728
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004729 /*
4730 * Issue #17237: m68k is a bit different from most architectures in
4731 * that objects do not use "natural alignment" - for example, int and
4732 * long are only aligned at 2-byte boundaries. Therefore the assert()
4733 * won't work; also, tests have shown that skipping the "optimised
4734 * version" will even speed up m68k.
4735 */
4736#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004737#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004738 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4739 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004740 /* Fast path, see in STRINGLIB(utf8_decode) for
4741 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004742 /* Help allocation */
4743 const char *_p = p;
4744 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 while (_p < aligned_end) {
4746 unsigned long value = *(const unsigned long *) _p;
4747 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004748 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004749 *((unsigned long *)q) = value;
4750 _p += SIZEOF_LONG;
4751 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004752 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 p = _p;
4754 while (p < end) {
4755 if ((unsigned char)*p & 0x80)
4756 break;
4757 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004758 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004759 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004760 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004761#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004762#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 while (p < end) {
4764 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4765 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004766 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004767 /* Help allocation */
4768 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004769 while (_p < aligned_end) {
4770 unsigned long value = *(unsigned long *) _p;
4771 if (value & ASCII_CHAR_MASK)
4772 break;
4773 _p += SIZEOF_LONG;
4774 }
4775 p = _p;
4776 if (_p == end)
4777 break;
4778 }
4779 if ((unsigned char)*p & 0x80)
4780 break;
4781 ++p;
4782 }
4783 memcpy(dest, start, p - start);
4784 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004785}
Antoine Pitrouab868312009-01-10 15:40:25 +00004786
Victor Stinner785938e2011-12-11 20:09:03 +01004787PyObject *
4788PyUnicode_DecodeUTF8Stateful(const char *s,
4789 Py_ssize_t size,
4790 const char *errors,
4791 Py_ssize_t *consumed)
4792{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004793 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004794 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796
4797 Py_ssize_t startinpos;
4798 Py_ssize_t endinpos;
4799 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004800 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004802 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004803
4804 if (size == 0) {
4805 if (consumed)
4806 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004807 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004808 }
4809
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004810 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4811 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004812 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813 *consumed = 1;
4814 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004815 }
4816
Victor Stinner8f674cc2013-04-17 23:02:17 +02004817 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004818 writer.min_length = size;
4819 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004820 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004821
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004822 writer.pos = ascii_decode(s, end, writer.data);
4823 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004824 while (s < end) {
4825 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004826 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004827
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004829 if (PyUnicode_IS_ASCII(writer.buffer))
4830 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004831 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004832 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004834 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 } else {
4836 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004837 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004838 }
4839
4840 switch (ch) {
4841 case 0:
4842 if (s == end || consumed)
4843 goto End;
4844 errmsg = "unexpected end of data";
4845 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004846 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 break;
4848 case 1:
4849 errmsg = "invalid start byte";
4850 startinpos = s - starts;
4851 endinpos = startinpos + 1;
4852 break;
4853 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004854 case 3:
4855 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856 errmsg = "invalid continuation byte";
4857 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004858 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004859 break;
4860 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004861 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004862 goto onError;
4863 continue;
4864 }
4865
Victor Stinner1d65d912015-10-05 13:43:50 +02004866 if (error_handler == _Py_ERROR_UNKNOWN)
4867 error_handler = get_error_handler(errors);
4868
4869 switch (error_handler) {
4870 case _Py_ERROR_IGNORE:
4871 s += (endinpos - startinpos);
4872 break;
4873
4874 case _Py_ERROR_REPLACE:
4875 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4876 goto onError;
4877 s += (endinpos - startinpos);
4878 break;
4879
4880 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004881 {
4882 Py_ssize_t i;
4883
Victor Stinner1d65d912015-10-05 13:43:50 +02004884 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4885 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004886 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004887 ch = (Py_UCS4)(unsigned char)(starts[i]);
4888 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4889 ch + 0xdc00);
4890 writer.pos++;
4891 }
4892 s += (endinpos - startinpos);
4893 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004894 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004895
4896 default:
4897 if (unicode_decode_call_errorhandler_writer(
4898 errors, &error_handler_obj,
4899 "utf-8", errmsg,
4900 &starts, &end, &startinpos, &endinpos, &exc, &s,
4901 &writer))
4902 goto onError;
4903 }
Victor Stinner785938e2011-12-11 20:09:03 +01004904 }
4905
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004906End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004907 if (consumed)
4908 *consumed = s - starts;
4909
Victor Stinner1d65d912015-10-05 13:43:50 +02004910 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004912 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004913
4914onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004915 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004916 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004917 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004919}
4920
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004921
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004922/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4923 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004924
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004925 On success, write a pointer to a newly allocated wide character string into
4926 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4927 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004928
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004929 On memory allocation failure, return -1.
4930
4931 On decoding error (if surrogateescape is zero), return -2. If wlen is
4932 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4933 is not NULL, write the decoding error message into *reason. */
4934int
4935_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
4936 const char **reason, int surrogateescape)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004937{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004938 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004939 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004940 wchar_t *unicode;
4941 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942
4943 /* Note: size will always be longer than the resulting Unicode
4944 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004945 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004946 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004947 }
4948
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004949 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004950 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004951 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004952 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004953
4954 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004955 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004957 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004958 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004959#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004961#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004963#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004964 if (ch > 0xFF) {
4965#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004966 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004967#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004968 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004969 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4971 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4972#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004973 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 else {
4975 if (!ch && s == e)
4976 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004977 if (!surrogateescape) {
4978 PyMem_RawFree(unicode );
4979 if (reason != NULL) {
4980 switch (ch) {
4981 case 0:
4982 *reason = "unexpected end of data";
4983 break;
4984 case 1:
4985 *reason = "invalid start byte";
4986 break;
4987 /* 2, 3, 4 */
4988 default:
4989 *reason = "invalid continuation byte";
4990 break;
4991 }
4992 }
4993 if (wlen != NULL) {
4994 *wlen = s - orig_s;
4995 }
4996 return -2;
4997 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004998 /* surrogateescape */
4999 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5000 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005001 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005003 if (wlen) {
5004 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005005 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005006 *wstr = unicode;
5007 return 0;
5008}
5009
5010wchar_t*
5011_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5012{
5013 wchar_t *wstr;
5014 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5015 if (res != 0) {
5016 return NULL;
5017 }
5018 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005019}
5020
Antoine Pitrouab868312009-01-10 15:40:25 +00005021
Victor Stinnere47e6982017-12-21 15:45:16 +01005022/* UTF-8 encoder using the surrogateescape error handler .
5023
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005024 On success, return 0 and write the newly allocated character string (use
5025 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005026
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005027 On encoding failure, return -2 and write the position of the invalid
5028 surrogate character into *error_pos (if error_pos is set) and the decoding
5029 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005030
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005031 On memory allocation failure, return -1. */
5032int
5033_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
5034 const char **reason, int raw_malloc, int surrogateescape)
Victor Stinnere47e6982017-12-21 15:45:16 +01005035{
5036 const Py_ssize_t max_char_size = 4;
5037 Py_ssize_t len = wcslen(text);
5038
5039 assert(len >= 0);
5040
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005041 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5042 return -1;
5043 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005044 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005045 if (raw_malloc) {
5046 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005047 }
5048 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005049 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005050 }
5051 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005052 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005053 }
5054
5055 char *p = bytes;
5056 Py_ssize_t i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005057 for (i = 0; i < len; i++) {
5058 Py_UCS4 ch = text[i];
Victor Stinnere47e6982017-12-21 15:45:16 +01005059
5060 if (ch < 0x80) {
5061 /* Encode ASCII */
5062 *p++ = (char) ch;
5063
5064 }
5065 else if (ch < 0x0800) {
5066 /* Encode Latin-1 */
5067 *p++ = (char)(0xc0 | (ch >> 6));
5068 *p++ = (char)(0x80 | (ch & 0x3f));
5069 }
5070 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5071 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005072 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005073 if (error_pos != NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005074 *error_pos = (size_t)i;
Victor Stinnere47e6982017-12-21 15:45:16 +01005075 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005076 if (reason != NULL) {
5077 *reason = "encoding error";
5078 }
5079 if (raw_malloc) {
5080 PyMem_RawFree(bytes);
5081 }
5082 else {
5083 PyMem_Free(bytes);
5084 }
5085 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005086 }
5087 *p++ = (char)(ch & 0xff);
5088 }
5089 else if (ch < 0x10000) {
5090 *p++ = (char)(0xe0 | (ch >> 12));
5091 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5092 *p++ = (char)(0x80 | (ch & 0x3f));
5093 }
5094 else { /* ch >= 0x10000 */
5095 assert(ch <= MAX_UNICODE);
5096 /* Encode UCS4 Unicode ordinals */
5097 *p++ = (char)(0xf0 | (ch >> 18));
5098 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5099 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5100 *p++ = (char)(0x80 | (ch & 0x3f));
5101 }
5102 }
5103 *p++ = '\0';
5104
5105 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005106 char *bytes2;
5107 if (raw_malloc) {
5108 bytes2 = PyMem_RawRealloc(bytes, final_size);
5109 }
5110 else {
5111 bytes2 = PyMem_Realloc(bytes, final_size);
5112 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005113 if (bytes2 == NULL) {
5114 if (error_pos != NULL) {
5115 *error_pos = (size_t)-1;
5116 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005117 if (raw_malloc) {
5118 PyMem_RawFree(bytes);
5119 }
5120 else {
5121 PyMem_Free(bytes);
5122 }
5123 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005124 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005125 *str = bytes2;
5126 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005127}
5128
5129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005130/* Primary internal function which creates utf8 encoded bytes objects.
5131
5132 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005133 and allocate exactly as much space needed at the end. Else allocate the
5134 maximum possible needed (4 result bytes per Unicode character), and return
5135 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005136*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005137PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005138_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005139{
Victor Stinner6099a032011-12-18 14:22:26 +01005140 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005141 void *data;
5142 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005144 if (!PyUnicode_Check(unicode)) {
5145 PyErr_BadArgument();
5146 return NULL;
5147 }
5148
5149 if (PyUnicode_READY(unicode) == -1)
5150 return NULL;
5151
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005152 if (PyUnicode_UTF8(unicode))
5153 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5154 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005155
5156 kind = PyUnicode_KIND(unicode);
5157 data = PyUnicode_DATA(unicode);
5158 size = PyUnicode_GET_LENGTH(unicode);
5159
Benjamin Petersonead6b532011-12-20 17:23:42 -06005160 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005161 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005162 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005163 case PyUnicode_1BYTE_KIND:
5164 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5165 assert(!PyUnicode_IS_ASCII(unicode));
5166 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5167 case PyUnicode_2BYTE_KIND:
5168 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5169 case PyUnicode_4BYTE_KIND:
5170 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005171 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005172}
5173
Alexander Belopolsky40018472011-02-26 01:02:56 +00005174PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005175PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5176 Py_ssize_t size,
5177 const char *errors)
5178{
5179 PyObject *v, *unicode;
5180
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005181 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005182 if (unicode == NULL)
5183 return NULL;
5184 v = _PyUnicode_AsUTF8String(unicode, errors);
5185 Py_DECREF(unicode);
5186 return v;
5187}
5188
5189PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005190PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005192 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005193}
5194
Walter Dörwald41980ca2007-08-16 21:55:45 +00005195/* --- UTF-32 Codec ------------------------------------------------------- */
5196
5197PyObject *
5198PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005199 Py_ssize_t size,
5200 const char *errors,
5201 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005202{
5203 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5204}
5205
5206PyObject *
5207PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005208 Py_ssize_t size,
5209 const char *errors,
5210 int *byteorder,
5211 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005212{
5213 const char *starts = s;
5214 Py_ssize_t startinpos;
5215 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005216 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005217 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005218 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005219 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005221 PyObject *errorHandler = NULL;
5222 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005223
Walter Dörwald41980ca2007-08-16 21:55:45 +00005224 q = (unsigned char *)s;
5225 e = q + size;
5226
5227 if (byteorder)
5228 bo = *byteorder;
5229
5230 /* Check for BOM marks (U+FEFF) in the input and adjust current
5231 byte order setting accordingly. In native mode, the leading BOM
5232 mark is skipped, in all other modes, it is copied to the output
5233 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005234 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005235 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005236 if (bom == 0x0000FEFF) {
5237 bo = -1;
5238 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005240 else if (bom == 0xFFFE0000) {
5241 bo = 1;
5242 q += 4;
5243 }
5244 if (byteorder)
5245 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005246 }
5247
Victor Stinnere64322e2012-10-30 23:12:47 +01005248 if (q == e) {
5249 if (consumed)
5250 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005251 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005252 }
5253
Victor Stinnere64322e2012-10-30 23:12:47 +01005254#ifdef WORDS_BIGENDIAN
5255 le = bo < 0;
5256#else
5257 le = bo <= 0;
5258#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005259 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005260
Victor Stinner8f674cc2013-04-17 23:02:17 +02005261 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005262 writer.min_length = (e - q + 3) / 4;
5263 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005264 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005265
Victor Stinnere64322e2012-10-30 23:12:47 +01005266 while (1) {
5267 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005268 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005269
Victor Stinnere64322e2012-10-30 23:12:47 +01005270 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005271 enum PyUnicode_Kind kind = writer.kind;
5272 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005273 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005274 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005275 if (le) {
5276 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005277 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005278 if (ch > maxch)
5279 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005280 if (kind != PyUnicode_1BYTE_KIND &&
5281 Py_UNICODE_IS_SURROGATE(ch))
5282 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005283 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005284 q += 4;
5285 } while (q <= last);
5286 }
5287 else {
5288 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005289 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005290 if (ch > maxch)
5291 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005292 if (kind != PyUnicode_1BYTE_KIND &&
5293 Py_UNICODE_IS_SURROGATE(ch))
5294 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005295 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005296 q += 4;
5297 } while (q <= last);
5298 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005299 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005300 }
5301
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005302 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005303 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005304 startinpos = ((const char *)q) - starts;
5305 endinpos = startinpos + 4;
5306 }
5307 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005308 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005310 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005311 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005312 startinpos = ((const char *)q) - starts;
5313 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005314 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005315 else {
5316 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005317 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005318 goto onError;
5319 q += 4;
5320 continue;
5321 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005322 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005323 startinpos = ((const char *)q) - starts;
5324 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005326
5327 /* The remaining input chars are ignored if the callback
5328 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005331 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005333 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005335 }
5336
Walter Dörwald41980ca2007-08-16 21:55:45 +00005337 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339
Walter Dörwald41980ca2007-08-16 21:55:45 +00005340 Py_XDECREF(errorHandler);
5341 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005342 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005345 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005346 Py_XDECREF(errorHandler);
5347 Py_XDECREF(exc);
5348 return NULL;
5349}
5350
5351PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005352_PyUnicode_EncodeUTF32(PyObject *str,
5353 const char *errors,
5354 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005355{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005356 enum PyUnicode_Kind kind;
5357 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005358 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005359 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005360 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005361#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005362 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005364 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005365#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005366 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 PyObject *errorHandler = NULL;
5369 PyObject *exc = NULL;
5370 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005371
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005372 if (!PyUnicode_Check(str)) {
5373 PyErr_BadArgument();
5374 return NULL;
5375 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005376 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005377 return NULL;
5378 kind = PyUnicode_KIND(str);
5379 data = PyUnicode_DATA(str);
5380 len = PyUnicode_GET_LENGTH(str);
5381
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005382 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005383 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005384 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005385 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005386 if (v == NULL)
5387 return NULL;
5388
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005389 /* output buffer is 4-bytes aligned */
5390 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005391 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005392 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005393 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005394 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005395 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005396
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005397 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005398 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005399 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005400 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005401 else
5402 encoding = "utf-32";
5403
5404 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5406 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005407 }
5408
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005409 pos = 0;
5410 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005411 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005412
5413 if (kind == PyUnicode_2BYTE_KIND) {
5414 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5415 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005416 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417 else {
5418 assert(kind == PyUnicode_4BYTE_KIND);
5419 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5420 &out, native_ordering);
5421 }
5422 if (pos == len)
5423 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005424
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005425 rep = unicode_encode_call_errorhandler(
5426 errors, &errorHandler,
5427 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005428 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005429 if (!rep)
5430 goto error;
5431
5432 if (PyBytes_Check(rep)) {
5433 repsize = PyBytes_GET_SIZE(rep);
5434 if (repsize & 3) {
5435 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005436 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005437 "surrogates not allowed");
5438 goto error;
5439 }
5440 moreunits = repsize / 4;
5441 }
5442 else {
5443 assert(PyUnicode_Check(rep));
5444 if (PyUnicode_READY(rep) < 0)
5445 goto error;
5446 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5447 if (!PyUnicode_IS_ASCII(rep)) {
5448 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005449 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005450 "surrogates not allowed");
5451 goto error;
5452 }
5453 }
5454
5455 /* four bytes are reserved for each surrogate */
5456 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005457 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005458 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005459 /* integer overflow */
5460 PyErr_NoMemory();
5461 goto error;
5462 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005463 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005465 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005466 }
5467
5468 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005469 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005470 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005471 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005473 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5474 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005475 }
5476
5477 Py_CLEAR(rep);
5478 }
5479
5480 /* Cut back to size actually needed. This is necessary for, for example,
5481 encoding of a string containing isolated surrogates and the 'ignore'
5482 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005483 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005484 if (nsize != PyBytes_GET_SIZE(v))
5485 _PyBytes_Resize(&v, nsize);
5486 Py_XDECREF(errorHandler);
5487 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005488 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005489 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005490 error:
5491 Py_XDECREF(rep);
5492 Py_XDECREF(errorHandler);
5493 Py_XDECREF(exc);
5494 Py_XDECREF(v);
5495 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005496}
5497
Alexander Belopolsky40018472011-02-26 01:02:56 +00005498PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005499PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5500 Py_ssize_t size,
5501 const char *errors,
5502 int byteorder)
5503{
5504 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005505 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005506 if (tmp == NULL)
5507 return NULL;
5508 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5509 Py_DECREF(tmp);
5510 return result;
5511}
5512
5513PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005514PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005515{
Victor Stinnerb960b342011-11-20 19:12:52 +01005516 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005517}
5518
Guido van Rossumd57fd912000-03-10 22:53:23 +00005519/* --- UTF-16 Codec ------------------------------------------------------- */
5520
Tim Peters772747b2001-08-09 22:21:55 +00005521PyObject *
5522PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005523 Py_ssize_t size,
5524 const char *errors,
5525 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005526{
Walter Dörwald69652032004-09-07 20:24:22 +00005527 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5528}
5529
5530PyObject *
5531PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005532 Py_ssize_t size,
5533 const char *errors,
5534 int *byteorder,
5535 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005536{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005537 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005538 Py_ssize_t startinpos;
5539 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005540 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005541 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005542 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005543 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005544 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005545 PyObject *errorHandler = NULL;
5546 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005547 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548
Tim Peters772747b2001-08-09 22:21:55 +00005549 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005550 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551
5552 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005553 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005555 /* Check for BOM marks (U+FEFF) in the input and adjust current
5556 byte order setting accordingly. In native mode, the leading BOM
5557 mark is skipped, in all other modes, it is copied to the output
5558 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005559 if (bo == 0 && size >= 2) {
5560 const Py_UCS4 bom = (q[1] << 8) | q[0];
5561 if (bom == 0xFEFF) {
5562 q += 2;
5563 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005564 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005565 else if (bom == 0xFFFE) {
5566 q += 2;
5567 bo = 1;
5568 }
5569 if (byteorder)
5570 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005572
Antoine Pitrou63065d72012-05-15 23:48:04 +02005573 if (q == e) {
5574 if (consumed)
5575 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005576 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005577 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005578
Christian Heimes743e0cd2012-10-17 23:52:17 +02005579#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005580 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005581 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005582#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005583 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005584 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005585#endif
Tim Peters772747b2001-08-09 22:21:55 +00005586
Antoine Pitrou63065d72012-05-15 23:48:04 +02005587 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005588 character count normally. Error handler will take care of
5589 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005590 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005591 writer.min_length = (e - q + 1) / 2;
5592 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005593 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005594
Antoine Pitrou63065d72012-05-15 23:48:04 +02005595 while (1) {
5596 Py_UCS4 ch = 0;
5597 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005598 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005600 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005601 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005602 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005603 native_ordering);
5604 else
5605 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005606 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 native_ordering);
5608 } else if (kind == PyUnicode_2BYTE_KIND) {
5609 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005610 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005611 native_ordering);
5612 } else {
5613 assert(kind == PyUnicode_4BYTE_KIND);
5614 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005615 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005616 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005617 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005618 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005619
Antoine Pitrou63065d72012-05-15 23:48:04 +02005620 switch (ch)
5621 {
5622 case 0:
5623 /* remaining byte at the end? (size should be even) */
5624 if (q == e || consumed)
5625 goto End;
5626 errmsg = "truncated data";
5627 startinpos = ((const char *)q) - starts;
5628 endinpos = ((const char *)e) - starts;
5629 break;
5630 /* The remaining input chars are ignored if the callback
5631 chooses to skip the input */
5632 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005633 q -= 2;
5634 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005635 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005636 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005637 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005638 endinpos = ((const char *)e) - starts;
5639 break;
5640 case 2:
5641 errmsg = "illegal encoding";
5642 startinpos = ((const char *)q) - 2 - starts;
5643 endinpos = startinpos + 2;
5644 break;
5645 case 3:
5646 errmsg = "illegal UTF-16 surrogate";
5647 startinpos = ((const char *)q) - 4 - starts;
5648 endinpos = startinpos + 2;
5649 break;
5650 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005651 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005652 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005653 continue;
5654 }
5655
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005656 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005657 errors,
5658 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005659 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005660 &starts,
5661 (const char **)&e,
5662 &startinpos,
5663 &endinpos,
5664 &exc,
5665 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005666 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005667 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 }
5669
Antoine Pitrou63065d72012-05-15 23:48:04 +02005670End:
Walter Dörwald69652032004-09-07 20:24:22 +00005671 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005673
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 Py_XDECREF(errorHandler);
5675 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005676 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677
Benjamin Peterson29060642009-01-31 22:14:21 +00005678 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005679 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005680 Py_XDECREF(errorHandler);
5681 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682 return NULL;
5683}
5684
Tim Peters772747b2001-08-09 22:21:55 +00005685PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005686_PyUnicode_EncodeUTF16(PyObject *str,
5687 const char *errors,
5688 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005690 enum PyUnicode_Kind kind;
5691 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005692 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005693 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005694 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005695 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005696#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005697 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005698#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005699 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005700#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005701 const char *encoding;
5702 Py_ssize_t nsize, pos;
5703 PyObject *errorHandler = NULL;
5704 PyObject *exc = NULL;
5705 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005706
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005707 if (!PyUnicode_Check(str)) {
5708 PyErr_BadArgument();
5709 return NULL;
5710 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005711 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005712 return NULL;
5713 kind = PyUnicode_KIND(str);
5714 data = PyUnicode_DATA(str);
5715 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005716
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005717 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005718 if (kind == PyUnicode_4BYTE_KIND) {
5719 const Py_UCS4 *in = (const Py_UCS4 *)data;
5720 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005721 while (in < end) {
5722 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005723 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005724 }
5725 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005726 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005727 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005728 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005729 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005730 nsize = len + pairs + (byteorder == 0);
5731 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005732 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005734 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005736 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005737 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005738 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005739 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005740 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005741 }
5742 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005743 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005744 }
Tim Peters772747b2001-08-09 22:21:55 +00005745
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005746 if (kind == PyUnicode_1BYTE_KIND) {
5747 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5748 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005749 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005750
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005751 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005752 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005753 }
5754 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005755 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005756 }
5757 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005758 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005759 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005760
5761 pos = 0;
5762 while (pos < len) {
5763 Py_ssize_t repsize, moreunits;
5764
5765 if (kind == PyUnicode_2BYTE_KIND) {
5766 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5767 &out, native_ordering);
5768 }
5769 else {
5770 assert(kind == PyUnicode_4BYTE_KIND);
5771 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5772 &out, native_ordering);
5773 }
5774 if (pos == len)
5775 break;
5776
5777 rep = unicode_encode_call_errorhandler(
5778 errors, &errorHandler,
5779 encoding, "surrogates not allowed",
5780 str, &exc, pos, pos + 1, &pos);
5781 if (!rep)
5782 goto error;
5783
5784 if (PyBytes_Check(rep)) {
5785 repsize = PyBytes_GET_SIZE(rep);
5786 if (repsize & 1) {
5787 raise_encode_exception(&exc, encoding,
5788 str, pos - 1, pos,
5789 "surrogates not allowed");
5790 goto error;
5791 }
5792 moreunits = repsize / 2;
5793 }
5794 else {
5795 assert(PyUnicode_Check(rep));
5796 if (PyUnicode_READY(rep) < 0)
5797 goto error;
5798 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5799 if (!PyUnicode_IS_ASCII(rep)) {
5800 raise_encode_exception(&exc, encoding,
5801 str, pos - 1, pos,
5802 "surrogates not allowed");
5803 goto error;
5804 }
5805 }
5806
5807 /* two bytes are reserved for each surrogate */
5808 if (moreunits > 1) {
5809 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005810 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005811 /* integer overflow */
5812 PyErr_NoMemory();
5813 goto error;
5814 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005815 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005816 goto error;
5817 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5818 }
5819
5820 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005821 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005822 out += moreunits;
5823 } else /* rep is unicode */ {
5824 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5825 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5826 &out, native_ordering);
5827 }
5828
5829 Py_CLEAR(rep);
5830 }
5831
5832 /* Cut back to size actually needed. This is necessary for, for example,
5833 encoding of a string containing isolated surrogates and the 'ignore' handler
5834 is used. */
5835 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5836 if (nsize != PyBytes_GET_SIZE(v))
5837 _PyBytes_Resize(&v, nsize);
5838 Py_XDECREF(errorHandler);
5839 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005840 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005841 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005842 error:
5843 Py_XDECREF(rep);
5844 Py_XDECREF(errorHandler);
5845 Py_XDECREF(exc);
5846 Py_XDECREF(v);
5847 return NULL;
5848#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849}
5850
Alexander Belopolsky40018472011-02-26 01:02:56 +00005851PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005852PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5853 Py_ssize_t size,
5854 const char *errors,
5855 int byteorder)
5856{
5857 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005858 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005859 if (tmp == NULL)
5860 return NULL;
5861 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5862 Py_DECREF(tmp);
5863 return result;
5864}
5865
5866PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005867PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005869 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870}
5871
5872/* --- Unicode Escape Codec ----------------------------------------------- */
5873
Fredrik Lundh06d12682001-01-24 07:59:11 +00005874static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005875
Alexander Belopolsky40018472011-02-26 01:02:56 +00005876PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005877_PyUnicode_DecodeUnicodeEscape(const char *s,
5878 Py_ssize_t size,
5879 const char *errors,
5880 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005882 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005883 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885 PyObject *errorHandler = NULL;
5886 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005887
Eric V. Smith42454af2016-10-31 09:22:08 -04005888 // so we can remember if we've seen an invalid escape char or not
5889 *first_invalid_escape = NULL;
5890
Victor Stinner62ec3312016-09-06 17:04:34 -07005891 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005892 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005893 }
5894 /* Escaped strings will always be longer than the resulting
5895 Unicode string, so we start with size here and then reduce the
5896 length after conversion to the true value.
5897 (but if the error callback returns a long replacement string
5898 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005899 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005900 writer.min_length = size;
5901 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5902 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005903 }
5904
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 end = s + size;
5906 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005907 unsigned char c = (unsigned char) *s++;
5908 Py_UCS4 ch;
5909 int count;
5910 Py_ssize_t startinpos;
5911 Py_ssize_t endinpos;
5912 const char *message;
5913
5914#define WRITE_ASCII_CHAR(ch) \
5915 do { \
5916 assert(ch <= 127); \
5917 assert(writer.pos < writer.size); \
5918 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5919 } while(0)
5920
5921#define WRITE_CHAR(ch) \
5922 do { \
5923 if (ch <= writer.maxchar) { \
5924 assert(writer.pos < writer.size); \
5925 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5926 } \
5927 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5928 goto onError; \
5929 } \
5930 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931
5932 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005933 if (c != '\\') {
5934 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 continue;
5936 }
5937
Victor Stinner62ec3312016-09-06 17:04:34 -07005938 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005940 if (s >= end) {
5941 message = "\\ at end of string";
5942 goto error;
5943 }
5944 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005945
Victor Stinner62ec3312016-09-06 17:04:34 -07005946 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005947 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005950 case '\n': continue;
5951 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5952 case '\'': WRITE_ASCII_CHAR('\''); continue;
5953 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5954 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005955 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005956 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5957 case 't': WRITE_ASCII_CHAR('\t'); continue;
5958 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5959 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005960 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005961 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005962 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005963 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 case '0': case '1': case '2': case '3':
5967 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005968 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005969 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005970 ch = (ch<<3) + *s++ - '0';
5971 if (s < end && '0' <= *s && *s <= '7') {
5972 ch = (ch<<3) + *s++ - '0';
5973 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005975 WRITE_CHAR(ch);
5976 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 /* hex escapes */
5979 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005981 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005982 message = "truncated \\xXX escape";
5983 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005987 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005988 message = "truncated \\uXXXX escape";
5989 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005992 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005993 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005994 message = "truncated \\UXXXXXXXX escape";
5995 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005996 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005997 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005998 ch <<= 4;
5999 if (c >= '0' && c <= '9') {
6000 ch += c - '0';
6001 }
6002 else if (c >= 'a' && c <= 'f') {
6003 ch += c - ('a' - 10);
6004 }
6005 else if (c >= 'A' && c <= 'F') {
6006 ch += c - ('A' - 10);
6007 }
6008 else {
6009 break;
6010 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006011 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006012 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006013 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006014 }
6015
6016 /* when we get here, ch is a 32-bit unicode character */
6017 if (ch > MAX_UNICODE) {
6018 message = "illegal Unicode character";
6019 goto error;
6020 }
6021
6022 WRITE_CHAR(ch);
6023 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006024
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006026 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006027 if (ucnhash_CAPI == NULL) {
6028 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006029 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6030 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006031 if (ucnhash_CAPI == NULL) {
6032 PyErr_SetString(
6033 PyExc_UnicodeError,
6034 "\\N escapes not supported (can't load unicodedata module)"
6035 );
6036 goto onError;
6037 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006038 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006039
6040 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006041 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006042 const char *start = ++s;
6043 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006044 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006045 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006047 namelen = s - start;
6048 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006050 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006051 ch = 0xffffffff; /* in case 'getcode' messes up */
6052 if (namelen <= INT_MAX &&
6053 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6054 &ch, 0)) {
6055 assert(ch <= MAX_UNICODE);
6056 WRITE_CHAR(ch);
6057 continue;
6058 }
6059 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006060 }
6061 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006062 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006063
6064 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006065 if (*first_invalid_escape == NULL) {
6066 *first_invalid_escape = s-1; /* Back up one char, since we've
6067 already incremented s. */
6068 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006069 WRITE_ASCII_CHAR('\\');
6070 WRITE_CHAR(c);
6071 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006073
6074 error:
6075 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006076 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006077 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006078 errors, &errorHandler,
6079 "unicodeescape", message,
6080 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006081 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006082 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006083 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006084 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006085
6086#undef WRITE_ASCII_CHAR
6087#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006089
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006090 Py_XDECREF(errorHandler);
6091 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006092 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006093
Benjamin Peterson29060642009-01-31 22:14:21 +00006094 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006095 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006096 Py_XDECREF(errorHandler);
6097 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098 return NULL;
6099}
6100
Eric V. Smith42454af2016-10-31 09:22:08 -04006101PyObject *
6102PyUnicode_DecodeUnicodeEscape(const char *s,
6103 Py_ssize_t size,
6104 const char *errors)
6105{
6106 const char *first_invalid_escape;
6107 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6108 &first_invalid_escape);
6109 if (result == NULL)
6110 return NULL;
6111 if (first_invalid_escape != NULL) {
6112 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6113 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006114 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006115 Py_DECREF(result);
6116 return NULL;
6117 }
6118 }
6119 return result;
6120}
6121
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006122/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123
Alexander Belopolsky40018472011-02-26 01:02:56 +00006124PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006128 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006130 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006131 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006132 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133
Ezio Melottie7f90372012-10-05 03:33:31 +03006134 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006135 escape.
6136
Ezio Melottie7f90372012-10-05 03:33:31 +03006137 For UCS1 strings it's '\xxx', 4 bytes per source character.
6138 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6139 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006140 */
6141
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006142 if (!PyUnicode_Check(unicode)) {
6143 PyErr_BadArgument();
6144 return NULL;
6145 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006146 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006148 }
Victor Stinner358af132015-10-12 22:36:57 +02006149
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006151 if (len == 0) {
6152 return PyBytes_FromStringAndSize(NULL, 0);
6153 }
6154
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006155 kind = PyUnicode_KIND(unicode);
6156 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006157 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6158 bytes, and 1 byte characters 4. */
6159 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006160 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006161 return PyErr_NoMemory();
6162 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006163 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006164 if (repr == NULL) {
6165 return NULL;
6166 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167
Victor Stinner62ec3312016-09-06 17:04:34 -07006168 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006169 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006170 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006171
Victor Stinner62ec3312016-09-06 17:04:34 -07006172 /* U+0000-U+00ff range */
6173 if (ch < 0x100) {
6174 if (ch >= ' ' && ch < 127) {
6175 if (ch != '\\') {
6176 /* Copy printable US ASCII as-is */
6177 *p++ = (char) ch;
6178 }
6179 /* Escape backslashes */
6180 else {
6181 *p++ = '\\';
6182 *p++ = '\\';
6183 }
6184 }
Victor Stinner358af132015-10-12 22:36:57 +02006185
Victor Stinner62ec3312016-09-06 17:04:34 -07006186 /* Map special whitespace to '\t', \n', '\r' */
6187 else if (ch == '\t') {
6188 *p++ = '\\';
6189 *p++ = 't';
6190 }
6191 else if (ch == '\n') {
6192 *p++ = '\\';
6193 *p++ = 'n';
6194 }
6195 else if (ch == '\r') {
6196 *p++ = '\\';
6197 *p++ = 'r';
6198 }
6199
6200 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6201 else {
6202 *p++ = '\\';
6203 *p++ = 'x';
6204 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6205 *p++ = Py_hexdigits[ch & 0x000F];
6206 }
Tim Petersced69f82003-09-16 20:30:58 +00006207 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006208 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006209 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006210 *p++ = '\\';
6211 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006212 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6213 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6214 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6215 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006217 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6218 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006219
Victor Stinner62ec3312016-09-06 17:04:34 -07006220 /* Make sure that the first two digits are zero */
6221 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006222 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006223 *p++ = 'U';
6224 *p++ = '0';
6225 *p++ = '0';
6226 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6227 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6228 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6229 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6230 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6231 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006232 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234
Victor Stinner62ec3312016-09-06 17:04:34 -07006235 assert(p - PyBytes_AS_STRING(repr) > 0);
6236 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6237 return NULL;
6238 }
6239 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240}
6241
Alexander Belopolsky40018472011-02-26 01:02:56 +00006242PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006243PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6244 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006246 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006247 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006248 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006250 }
6251
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006252 result = PyUnicode_AsUnicodeEscapeString(tmp);
6253 Py_DECREF(tmp);
6254 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255}
6256
6257/* --- Raw Unicode Escape Codec ------------------------------------------- */
6258
Alexander Belopolsky40018472011-02-26 01:02:56 +00006259PyObject *
6260PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006261 Py_ssize_t size,
6262 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006264 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006265 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006267 PyObject *errorHandler = NULL;
6268 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006269
Victor Stinner62ec3312016-09-06 17:04:34 -07006270 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006271 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006272 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006273
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274 /* Escaped strings will always be longer than the resulting
6275 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006276 length after conversion to the true value. (But decoding error
6277 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006278 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006279 writer.min_length = size;
6280 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6281 goto onError;
6282 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006283
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284 end = s + size;
6285 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006286 unsigned char c = (unsigned char) *s++;
6287 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006288 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006289 Py_ssize_t startinpos;
6290 Py_ssize_t endinpos;
6291 const char *message;
6292
6293#define WRITE_CHAR(ch) \
6294 do { \
6295 if (ch <= writer.maxchar) { \
6296 assert(writer.pos < writer.size); \
6297 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6298 } \
6299 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6300 goto onError; \
6301 } \
6302 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303
Benjamin Peterson29060642009-01-31 22:14:21 +00006304 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006305 if (c != '\\' || s >= end) {
6306 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006309
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 c = (unsigned char) *s++;
6311 if (c == 'u') {
6312 count = 4;
6313 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006314 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006315 else if (c == 'U') {
6316 count = 8;
6317 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006318 }
6319 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006320 assert(writer.pos < writer.size);
6321 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6322 WRITE_CHAR(c);
6323 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006324 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006325 startinpos = s - starts - 2;
6326
6327 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6328 for (ch = 0; count && s < end; ++s, --count) {
6329 c = (unsigned char)*s;
6330 ch <<= 4;
6331 if (c >= '0' && c <= '9') {
6332 ch += c - '0';
6333 }
6334 else if (c >= 'a' && c <= 'f') {
6335 ch += c - ('a' - 10);
6336 }
6337 else if (c >= 'A' && c <= 'F') {
6338 ch += c - ('A' - 10);
6339 }
6340 else {
6341 break;
6342 }
6343 }
6344 if (!count) {
6345 if (ch <= MAX_UNICODE) {
6346 WRITE_CHAR(ch);
6347 continue;
6348 }
6349 message = "\\Uxxxxxxxx out of range";
6350 }
6351
6352 endinpos = s-starts;
6353 writer.min_length = end - s + writer.pos;
6354 if (unicode_decode_call_errorhandler_writer(
6355 errors, &errorHandler,
6356 "rawunicodeescape", message,
6357 &starts, &end, &startinpos, &endinpos, &exc, &s,
6358 &writer)) {
6359 goto onError;
6360 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006361 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006362
6363#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006365 Py_XDECREF(errorHandler);
6366 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006367 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006368
Benjamin Peterson29060642009-01-31 22:14:21 +00006369 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006370 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371 Py_XDECREF(errorHandler);
6372 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006373 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006374
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375}
6376
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006377
Alexander Belopolsky40018472011-02-26 01:02:56 +00006378PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006379PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006380{
Victor Stinner62ec3312016-09-06 17:04:34 -07006381 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006382 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006383 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006384 int kind;
6385 void *data;
6386 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006388 if (!PyUnicode_Check(unicode)) {
6389 PyErr_BadArgument();
6390 return NULL;
6391 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006392 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006393 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006394 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006395 kind = PyUnicode_KIND(unicode);
6396 data = PyUnicode_DATA(unicode);
6397 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006398 if (kind == PyUnicode_1BYTE_KIND) {
6399 return PyBytes_FromStringAndSize(data, len);
6400 }
Victor Stinner0e368262011-11-10 20:12:49 +01006401
Victor Stinner62ec3312016-09-06 17:04:34 -07006402 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6403 bytes, and 1 byte characters 4. */
6404 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006405
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 if (len > PY_SSIZE_T_MAX / expandsize) {
6407 return PyErr_NoMemory();
6408 }
6409 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6410 if (repr == NULL) {
6411 return NULL;
6412 }
6413 if (len == 0) {
6414 return repr;
6415 }
6416
6417 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006418 for (pos = 0; pos < len; pos++) {
6419 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006420
Victor Stinner62ec3312016-09-06 17:04:34 -07006421 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6422 if (ch < 0x100) {
6423 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006424 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006425 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006426 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 *p++ = '\\';
6428 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006429 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6430 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6431 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6432 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006433 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006434 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6435 else {
6436 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6437 *p++ = '\\';
6438 *p++ = 'U';
6439 *p++ = '0';
6440 *p++ = '0';
6441 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6442 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6443 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6444 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6445 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6446 *p++ = Py_hexdigits[ch & 15];
6447 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006448 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006449
Victor Stinner62ec3312016-09-06 17:04:34 -07006450 assert(p > PyBytes_AS_STRING(repr));
6451 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6452 return NULL;
6453 }
6454 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006455}
6456
Alexander Belopolsky40018472011-02-26 01:02:56 +00006457PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006458PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6459 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006460{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006461 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006462 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006463 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006464 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006465 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6466 Py_DECREF(tmp);
6467 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006468}
6469
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006470/* --- Unicode Internal Codec ------------------------------------------- */
6471
Alexander Belopolsky40018472011-02-26 01:02:56 +00006472PyObject *
6473_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006474 Py_ssize_t size,
6475 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006476{
6477 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006478 Py_ssize_t startinpos;
6479 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006480 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006481 const char *end;
6482 const char *reason;
6483 PyObject *errorHandler = NULL;
6484 PyObject *exc = NULL;
6485
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006486 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006487 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006488 1))
6489 return NULL;
6490
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006491 if (size < 0) {
6492 PyErr_BadInternalCall();
6493 return NULL;
6494 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006495 if (size == 0)
6496 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006497
Victor Stinner8f674cc2013-04-17 23:02:17 +02006498 _PyUnicodeWriter_Init(&writer);
6499 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6500 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006502 }
6503 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006504
Victor Stinner8f674cc2013-04-17 23:02:17 +02006505 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006507 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006508 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006509 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006510 endinpos = end-starts;
6511 reason = "truncated input";
6512 goto error;
6513 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006514 /* We copy the raw representation one byte at a time because the
6515 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006516 ((char *) &uch)[0] = s[0];
6517 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006518#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006519 ((char *) &uch)[2] = s[2];
6520 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006521#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006522 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006523#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006524 /* We have to sanity check the raw data, otherwise doom looms for
6525 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006526 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006527 endinpos = s - starts + Py_UNICODE_SIZE;
6528 reason = "illegal code point (> 0x10FFFF)";
6529 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006530 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006531#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532 s += Py_UNICODE_SIZE;
6533#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006534 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006535 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006536 Py_UNICODE uch2;
6537 ((char *) &uch2)[0] = s[0];
6538 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006539 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006540 {
Victor Stinner551ac952011-11-29 22:58:13 +01006541 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006542 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006543 }
6544 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006545#endif
6546
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006547 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006548 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006549 continue;
6550
6551 error:
6552 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006553 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006554 errors, &errorHandler,
6555 "unicode_internal", reason,
6556 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006557 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006558 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006559 }
6560
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006561 Py_XDECREF(errorHandler);
6562 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006563 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006564
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006566 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006567 Py_XDECREF(errorHandler);
6568 Py_XDECREF(exc);
6569 return NULL;
6570}
6571
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572/* --- Latin-1 Codec ------------------------------------------------------ */
6573
Alexander Belopolsky40018472011-02-26 01:02:56 +00006574PyObject *
6575PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006576 Py_ssize_t size,
6577 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006578{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006579 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006580 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581}
6582
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006583/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006584static void
6585make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006586 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006587 PyObject *unicode,
6588 Py_ssize_t startpos, Py_ssize_t endpos,
6589 const char *reason)
6590{
6591 if (*exceptionObject == NULL) {
6592 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006593 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006594 encoding, unicode, startpos, endpos, reason);
6595 }
6596 else {
6597 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6598 goto onError;
6599 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6600 goto onError;
6601 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6602 goto onError;
6603 return;
6604 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006605 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006606 }
6607}
6608
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006610static void
6611raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006612 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006613 PyObject *unicode,
6614 Py_ssize_t startpos, Py_ssize_t endpos,
6615 const char *reason)
6616{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006617 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006618 encoding, unicode, startpos, endpos, reason);
6619 if (*exceptionObject != NULL)
6620 PyCodec_StrictErrors(*exceptionObject);
6621}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006622
6623/* error handling callback helper:
6624 build arguments, call the callback and check the arguments,
6625 put the result into newpos and return the replacement string, which
6626 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006627static PyObject *
6628unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006629 PyObject **errorHandler,
6630 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006632 Py_ssize_t startpos, Py_ssize_t endpos,
6633 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006635 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 PyObject *restuple;
6638 PyObject *resunicode;
6639
6640 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 }
6645
Benjamin Petersonbac79492012-01-14 13:34:47 -05006646 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 return NULL;
6648 len = PyUnicode_GET_LENGTH(unicode);
6649
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006650 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006655 restuple = PyObject_CallFunctionObjArgs(
6656 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006657 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006660 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006661 Py_DECREF(restuple);
6662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006664 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 &resunicode, newpos)) {
6666 Py_DECREF(restuple);
6667 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006669 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6670 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6671 Py_DECREF(restuple);
6672 return NULL;
6673 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006674 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006675 *newpos = len + *newpos;
6676 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006677 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 Py_DECREF(restuple);
6679 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006680 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681 Py_INCREF(resunicode);
6682 Py_DECREF(restuple);
6683 return resunicode;
6684}
6685
Alexander Belopolsky40018472011-02-26 01:02:56 +00006686static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006687unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006688 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006689 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006690{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006691 /* input state */
6692 Py_ssize_t pos=0, size;
6693 int kind;
6694 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695 /* pointer into the output */
6696 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006697 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6698 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006699 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006701 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006702 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006703 /* output object */
6704 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006705
Benjamin Petersonbac79492012-01-14 13:34:47 -05006706 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 return NULL;
6708 size = PyUnicode_GET_LENGTH(unicode);
6709 kind = PyUnicode_KIND(unicode);
6710 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 /* allocate enough for a simple encoding without
6712 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006713 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006714 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006715
6716 _PyBytesWriter_Init(&writer);
6717 str = _PyBytesWriter_Alloc(&writer, size);
6718 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006719 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006722 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006723
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006725 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006727 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006728 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006729 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006731 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006733 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006734 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006736
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006737 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006739
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006740 /* Only overallocate the buffer if it's not the last write */
6741 writer.overallocate = (collend < size);
6742
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006744 if (error_handler == _Py_ERROR_UNKNOWN)
6745 error_handler = get_error_handler(errors);
6746
6747 switch (error_handler) {
6748 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006749 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006751
6752 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006753 memset(str, '?', collend - collstart);
6754 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006755 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006756 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006757 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 break;
Victor Stinner50149202015-09-22 00:26:54 +02006759
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006760 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006761 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006762 writer.min_size -= (collend - collstart);
6763 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006764 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006765 if (str == NULL)
6766 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006767 pos = collend;
6768 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006769
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006770 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006771 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006772 writer.min_size -= (collend - collstart);
6773 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006774 unicode, collstart, collend);
6775 if (str == NULL)
6776 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006777 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 break;
Victor Stinner50149202015-09-22 00:26:54 +02006779
Victor Stinnerc3713e92015-09-29 12:32:13 +02006780 case _Py_ERROR_SURROGATEESCAPE:
6781 for (i = collstart; i < collend; ++i) {
6782 ch = PyUnicode_READ(kind, data, i);
6783 if (ch < 0xdc80 || 0xdcff < ch) {
6784 /* Not a UTF-8b surrogate */
6785 break;
6786 }
6787 *str++ = (char)(ch - 0xdc00);
6788 ++pos;
6789 }
6790 if (i >= collend)
6791 break;
6792 collstart = pos;
6793 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006794 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006795
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006797 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6798 encoding, reason, unicode, &exc,
6799 collstart, collend, &newpos);
6800 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006802
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006803 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006804 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006805
Victor Stinner6bd525b2015-10-09 13:10:05 +02006806 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006807 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006808 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006809 PyBytes_AS_STRING(rep),
6810 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006811 if (str == NULL)
6812 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006813 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 else {
6815 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006816
Victor Stinner6bd525b2015-10-09 13:10:05 +02006817 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006818 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006819
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006820 if (limit == 256 ?
6821 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6822 !PyUnicode_IS_ASCII(rep))
6823 {
6824 /* Not all characters are smaller than limit */
6825 raise_encode_exception(&exc, encoding, unicode,
6826 collstart, collend, reason);
6827 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006828 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006829 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6830 str = _PyBytesWriter_WriteBytes(&writer, str,
6831 PyUnicode_DATA(rep),
6832 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006834 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006835 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006836 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006837
6838 /* If overallocation was disabled, ensure that it was the last
6839 write. Otherwise, we missed an optimization */
6840 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006841 }
6842 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006843
Victor Stinner50149202015-09-22 00:26:54 +02006844 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006846 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006847
6848 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006849 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006850 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006851 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006852 Py_XDECREF(exc);
6853 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854}
6855
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006856/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006857PyObject *
6858PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006859 Py_ssize_t size,
6860 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006861{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006862 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006863 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006864 if (unicode == NULL)
6865 return NULL;
6866 result = unicode_encode_ucs1(unicode, errors, 256);
6867 Py_DECREF(unicode);
6868 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006869}
6870
Alexander Belopolsky40018472011-02-26 01:02:56 +00006871PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006872_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873{
6874 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 PyErr_BadArgument();
6876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006878 if (PyUnicode_READY(unicode) == -1)
6879 return NULL;
6880 /* Fast path: if it is a one-byte string, construct
6881 bytes object directly. */
6882 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6883 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6884 PyUnicode_GET_LENGTH(unicode));
6885 /* Non-Latin-1 characters present. Defer to above function to
6886 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006887 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006888}
6889
6890PyObject*
6891PyUnicode_AsLatin1String(PyObject *unicode)
6892{
6893 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894}
6895
6896/* --- 7-bit ASCII Codec -------------------------------------------------- */
6897
Alexander Belopolsky40018472011-02-26 01:02:56 +00006898PyObject *
6899PyUnicode_DecodeASCII(const char *s,
6900 Py_ssize_t size,
6901 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006903 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006904 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006905 int kind;
6906 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006907 Py_ssize_t startinpos;
6908 Py_ssize_t endinpos;
6909 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006910 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006911 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006912 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006913 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006914
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006916 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006917
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006919 if (size == 1 && (unsigned char)s[0] < 128)
6920 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006921
Victor Stinner8f674cc2013-04-17 23:02:17 +02006922 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006923 writer.min_length = size;
6924 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006925 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006926
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006927 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006928 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006929 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006930 writer.pos = outpos;
6931 if (writer.pos == size)
6932 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006933
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006934 s += writer.pos;
6935 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006936 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006937 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006939 PyUnicode_WRITE(kind, data, writer.pos, c);
6940 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006941 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006942 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006944
6945 /* byte outsize range 0x00..0x7f: call the error handler */
6946
6947 if (error_handler == _Py_ERROR_UNKNOWN)
6948 error_handler = get_error_handler(errors);
6949
6950 switch (error_handler)
6951 {
6952 case _Py_ERROR_REPLACE:
6953 case _Py_ERROR_SURROGATEESCAPE:
6954 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006955 but we may switch to UCS2 at the first write */
6956 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6957 goto onError;
6958 kind = writer.kind;
6959 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006960
6961 if (error_handler == _Py_ERROR_REPLACE)
6962 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6963 else
6964 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6965 writer.pos++;
6966 ++s;
6967 break;
6968
6969 case _Py_ERROR_IGNORE:
6970 ++s;
6971 break;
6972
6973 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 startinpos = s-starts;
6975 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006976 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006977 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 "ascii", "ordinal not in range(128)",
6979 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006980 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006982 kind = writer.kind;
6983 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006986 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006987 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006988 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006989
Benjamin Peterson29060642009-01-31 22:14:21 +00006990 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006991 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006992 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006993 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994 return NULL;
6995}
6996
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006997/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006998PyObject *
6999PyUnicode_EncodeASCII(const Py_UNICODE *p,
7000 Py_ssize_t size,
7001 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007002{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007003 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007004 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007005 if (unicode == NULL)
7006 return NULL;
7007 result = unicode_encode_ucs1(unicode, errors, 128);
7008 Py_DECREF(unicode);
7009 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007010}
7011
Alexander Belopolsky40018472011-02-26 01:02:56 +00007012PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007013_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007014{
7015 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007016 PyErr_BadArgument();
7017 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007018 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007019 if (PyUnicode_READY(unicode) == -1)
7020 return NULL;
7021 /* Fast path: if it is an ASCII-only string, construct bytes object
7022 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007023 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7025 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007026 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007027}
7028
7029PyObject *
7030PyUnicode_AsASCIIString(PyObject *unicode)
7031{
7032 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033}
7034
Steve Dowercc16be82016-09-08 10:35:16 -07007035#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007036
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007037/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007038
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007039#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040#define NEED_RETRY
7041#endif
7042
Victor Stinner3a50e702011-10-18 21:21:00 +02007043#ifndef WC_ERR_INVALID_CHARS
7044# define WC_ERR_INVALID_CHARS 0x0080
7045#endif
7046
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007047static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007048code_page_name(UINT code_page, PyObject **obj)
7049{
7050 *obj = NULL;
7051 if (code_page == CP_ACP)
7052 return "mbcs";
7053 if (code_page == CP_UTF7)
7054 return "CP_UTF7";
7055 if (code_page == CP_UTF8)
7056 return "CP_UTF8";
7057
7058 *obj = PyBytes_FromFormat("cp%u", code_page);
7059 if (*obj == NULL)
7060 return NULL;
7061 return PyBytes_AS_STRING(*obj);
7062}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064static DWORD
7065decode_code_page_flags(UINT code_page)
7066{
7067 if (code_page == CP_UTF7) {
7068 /* The CP_UTF7 decoder only supports flags=0 */
7069 return 0;
7070 }
7071 else
7072 return MB_ERR_INVALID_CHARS;
7073}
7074
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 * Decode a byte string from a Windows code page into unicode object in strict
7077 * mode.
7078 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007079 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7080 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007082static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007083decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007084 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 const char *in,
7086 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087{
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007089 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091
7092 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 assert(insize > 0);
7094 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7095 if (outsize <= 0)
7096 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097
7098 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007099 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007100 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007101 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007102 if (*v == NULL)
7103 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105 }
7106 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007107 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007109 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007110 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112 }
7113
7114 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007115 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7116 if (outsize <= 0)
7117 goto error;
7118 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007119
Victor Stinner3a50e702011-10-18 21:21:00 +02007120error:
7121 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7122 return -2;
7123 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007124 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007125}
7126
Victor Stinner3a50e702011-10-18 21:21:00 +02007127/*
7128 * Decode a byte string from a code page into unicode object with an error
7129 * handler.
7130 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007131 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 * UnicodeDecodeError exception and returns -1 on error.
7133 */
7134static int
7135decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007136 PyObject **v,
7137 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007138 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007139{
7140 const char *startin = in;
7141 const char *endin = in + size;
7142 const DWORD flags = decode_code_page_flags(code_page);
7143 /* Ideally, we should get reason from FormatMessage. This is the Windows
7144 2000 English version of the message. */
7145 const char *reason = "No mapping for the Unicode character exists "
7146 "in the target code page.";
7147 /* each step cannot decode more than 1 character, but a character can be
7148 represented as a surrogate pair */
7149 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007150 int insize;
7151 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 PyObject *errorHandler = NULL;
7153 PyObject *exc = NULL;
7154 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007155 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 DWORD err;
7157 int ret = -1;
7158
7159 assert(size > 0);
7160
7161 encoding = code_page_name(code_page, &encoding_obj);
7162 if (encoding == NULL)
7163 return -1;
7164
Victor Stinner7d00cc12014-03-17 23:08:06 +01007165 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7167 UnicodeDecodeError. */
7168 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7169 if (exc != NULL) {
7170 PyCodec_StrictErrors(exc);
7171 Py_CLEAR(exc);
7172 }
7173 goto error;
7174 }
7175
7176 if (*v == NULL) {
7177 /* Create unicode object */
7178 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7179 PyErr_NoMemory();
7180 goto error;
7181 }
Victor Stinnerab595942011-12-17 04:59:06 +01007182 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007183 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 if (*v == NULL)
7185 goto error;
7186 startout = PyUnicode_AS_UNICODE(*v);
7187 }
7188 else {
7189 /* Extend unicode object */
7190 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7191 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7192 PyErr_NoMemory();
7193 goto error;
7194 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007195 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 goto error;
7197 startout = PyUnicode_AS_UNICODE(*v) + n;
7198 }
7199
7200 /* Decode the byte string character per character */
7201 out = startout;
7202 while (in < endin)
7203 {
7204 /* Decode a character */
7205 insize = 1;
7206 do
7207 {
7208 outsize = MultiByteToWideChar(code_page, flags,
7209 in, insize,
7210 buffer, Py_ARRAY_LENGTH(buffer));
7211 if (outsize > 0)
7212 break;
7213 err = GetLastError();
7214 if (err != ERROR_NO_UNICODE_TRANSLATION
7215 && err != ERROR_INSUFFICIENT_BUFFER)
7216 {
7217 PyErr_SetFromWindowsErr(0);
7218 goto error;
7219 }
7220 insize++;
7221 }
7222 /* 4=maximum length of a UTF-8 sequence */
7223 while (insize <= 4 && (in + insize) <= endin);
7224
7225 if (outsize <= 0) {
7226 Py_ssize_t startinpos, endinpos, outpos;
7227
Victor Stinner7d00cc12014-03-17 23:08:06 +01007228 /* last character in partial decode? */
7229 if (in + insize >= endin && !final)
7230 break;
7231
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 startinpos = in - startin;
7233 endinpos = startinpos + 1;
7234 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007235 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 errors, &errorHandler,
7237 encoding, reason,
7238 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007239 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 {
7241 goto error;
7242 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007243 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 }
7245 else {
7246 in += insize;
7247 memcpy(out, buffer, outsize * sizeof(wchar_t));
7248 out += outsize;
7249 }
7250 }
7251
7252 /* write a NUL character at the end */
7253 *out = 0;
7254
7255 /* Extend unicode object */
7256 outsize = out - startout;
7257 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007258 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007260 /* (in - startin) <= size and size is an int */
7261 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007262
7263error:
7264 Py_XDECREF(encoding_obj);
7265 Py_XDECREF(errorHandler);
7266 Py_XDECREF(exc);
7267 return ret;
7268}
7269
Victor Stinner3a50e702011-10-18 21:21:00 +02007270static PyObject *
7271decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 const char *s, Py_ssize_t size,
7273 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274{
Victor Stinner76a31a62011-11-04 00:05:13 +01007275 PyObject *v = NULL;
7276 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 if (code_page < 0) {
7279 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7280 return NULL;
7281 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007282 if (size < 0) {
7283 PyErr_BadInternalCall();
7284 return NULL;
7285 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007286
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007287 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007288 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007289
Victor Stinner76a31a62011-11-04 00:05:13 +01007290 do
7291 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007293 if (size > INT_MAX) {
7294 chunk_size = INT_MAX;
7295 final = 0;
7296 done = 0;
7297 }
7298 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007299#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007300 {
7301 chunk_size = (int)size;
7302 final = (consumed == NULL);
7303 done = 1;
7304 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007305
Victor Stinner76a31a62011-11-04 00:05:13 +01007306 if (chunk_size == 0 && done) {
7307 if (v != NULL)
7308 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007309 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007310 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007311
Victor Stinner76a31a62011-11-04 00:05:13 +01007312 converted = decode_code_page_strict(code_page, &v,
7313 s, chunk_size);
7314 if (converted == -2)
7315 converted = decode_code_page_errors(code_page, &v,
7316 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007317 errors, final);
7318 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007319
7320 if (converted < 0) {
7321 Py_XDECREF(v);
7322 return NULL;
7323 }
7324
7325 if (consumed)
7326 *consumed += converted;
7327
7328 s += converted;
7329 size -= converted;
7330 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007331
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007332 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007333}
7334
Alexander Belopolsky40018472011-02-26 01:02:56 +00007335PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007336PyUnicode_DecodeCodePageStateful(int code_page,
7337 const char *s,
7338 Py_ssize_t size,
7339 const char *errors,
7340 Py_ssize_t *consumed)
7341{
7342 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7343}
7344
7345PyObject *
7346PyUnicode_DecodeMBCSStateful(const char *s,
7347 Py_ssize_t size,
7348 const char *errors,
7349 Py_ssize_t *consumed)
7350{
7351 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7352}
7353
7354PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007355PyUnicode_DecodeMBCS(const char *s,
7356 Py_ssize_t size,
7357 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007358{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007359 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7360}
7361
Victor Stinner3a50e702011-10-18 21:21:00 +02007362static DWORD
7363encode_code_page_flags(UINT code_page, const char *errors)
7364{
7365 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007366 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 }
7368 else if (code_page == CP_UTF7) {
7369 /* CP_UTF7 only supports flags=0 */
7370 return 0;
7371 }
7372 else {
7373 if (errors != NULL && strcmp(errors, "replace") == 0)
7374 return 0;
7375 else
7376 return WC_NO_BEST_FIT_CHARS;
7377 }
7378}
7379
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007380/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 * Encode a Unicode string to a Windows code page into a byte string in strict
7382 * mode.
7383 *
7384 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007385 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007387static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007388encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007389 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007391{
Victor Stinner554f3f02010-06-16 23:33:54 +00007392 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 BOOL *pusedDefaultChar = &usedDefaultChar;
7394 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007395 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007396 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 const DWORD flags = encode_code_page_flags(code_page, NULL);
7398 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007399 /* Create a substring so that we can get the UTF-16 representation
7400 of just the slice under consideration. */
7401 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007402
Martin v. Löwis3d325192011-11-04 18:23:06 +01007403 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007404
Victor Stinner3a50e702011-10-18 21:21:00 +02007405 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007406 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007408 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007409
Victor Stinner2fc507f2011-11-04 20:06:39 +01007410 substring = PyUnicode_Substring(unicode, offset, offset+len);
7411 if (substring == NULL)
7412 return -1;
7413 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7414 if (p == NULL) {
7415 Py_DECREF(substring);
7416 return -1;
7417 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007418 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007419
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007420 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007422 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 NULL, 0,
7424 NULL, pusedDefaultChar);
7425 if (outsize <= 0)
7426 goto error;
7427 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 if (pusedDefaultChar && *pusedDefaultChar) {
7429 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007431 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007432
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 if (*outbytes == NULL) {
7437 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441 }
7442 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007443 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 const Py_ssize_t n = PyBytes_Size(*outbytes);
7445 if (outsize > PY_SSIZE_T_MAX - n) {
7446 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007448 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7451 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007453 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007455 }
7456
7457 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007459 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007460 out, outsize,
7461 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007462 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 if (outsize <= 0)
7464 goto error;
7465 if (pusedDefaultChar && *pusedDefaultChar)
7466 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007467 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007468
Victor Stinner3a50e702011-10-18 21:21:00 +02007469error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007470 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7472 return -2;
7473 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007474 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007475}
7476
Victor Stinner3a50e702011-10-18 21:21:00 +02007477/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007478 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 * error handler.
7480 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007481 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 * -1 on other error.
7483 */
7484static int
7485encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007486 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007487 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007488{
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007490 Py_ssize_t pos = unicode_offset;
7491 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 /* Ideally, we should get reason from FormatMessage. This is the Windows
7493 2000 English version of the message. */
7494 const char *reason = "invalid character";
7495 /* 4=maximum length of a UTF-8 sequence */
7496 char buffer[4];
7497 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7498 Py_ssize_t outsize;
7499 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 PyObject *errorHandler = NULL;
7501 PyObject *exc = NULL;
7502 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007503 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 PyObject *rep;
7506 int ret = -1;
7507
7508 assert(insize > 0);
7509
7510 encoding = code_page_name(code_page, &encoding_obj);
7511 if (encoding == NULL)
7512 return -1;
7513
7514 if (errors == NULL || strcmp(errors, "strict") == 0) {
7515 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7516 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007517 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 if (exc != NULL) {
7519 PyCodec_StrictErrors(exc);
7520 Py_DECREF(exc);
7521 }
7522 Py_XDECREF(encoding_obj);
7523 return -1;
7524 }
7525
7526 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7527 pusedDefaultChar = &usedDefaultChar;
7528 else
7529 pusedDefaultChar = NULL;
7530
7531 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7532 PyErr_NoMemory();
7533 goto error;
7534 }
7535 outsize = insize * Py_ARRAY_LENGTH(buffer);
7536
7537 if (*outbytes == NULL) {
7538 /* Create string object */
7539 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7540 if (*outbytes == NULL)
7541 goto error;
7542 out = PyBytes_AS_STRING(*outbytes);
7543 }
7544 else {
7545 /* Extend string object */
7546 Py_ssize_t n = PyBytes_Size(*outbytes);
7547 if (n > PY_SSIZE_T_MAX - outsize) {
7548 PyErr_NoMemory();
7549 goto error;
7550 }
7551 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7552 goto error;
7553 out = PyBytes_AS_STRING(*outbytes) + n;
7554 }
7555
7556 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007557 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007558 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007559 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7560 wchar_t chars[2];
7561 int charsize;
7562 if (ch < 0x10000) {
7563 chars[0] = (wchar_t)ch;
7564 charsize = 1;
7565 }
7566 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007567 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7568 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007569 charsize = 2;
7570 }
7571
Victor Stinner3a50e702011-10-18 21:21:00 +02007572 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007573 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007574 buffer, Py_ARRAY_LENGTH(buffer),
7575 NULL, pusedDefaultChar);
7576 if (outsize > 0) {
7577 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7578 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007579 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 memcpy(out, buffer, outsize);
7581 out += outsize;
7582 continue;
7583 }
7584 }
7585 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7586 PyErr_SetFromWindowsErr(0);
7587 goto error;
7588 }
7589
Victor Stinner3a50e702011-10-18 21:21:00 +02007590 rep = unicode_encode_call_errorhandler(
7591 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007592 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007593 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007594 if (rep == NULL)
7595 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007596 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007597
7598 if (PyBytes_Check(rep)) {
7599 outsize = PyBytes_GET_SIZE(rep);
7600 if (outsize != 1) {
7601 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7602 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7603 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7604 Py_DECREF(rep);
7605 goto error;
7606 }
7607 out = PyBytes_AS_STRING(*outbytes) + offset;
7608 }
7609 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7610 out += outsize;
7611 }
7612 else {
7613 Py_ssize_t i;
7614 enum PyUnicode_Kind kind;
7615 void *data;
7616
Benjamin Petersonbac79492012-01-14 13:34:47 -05007617 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007618 Py_DECREF(rep);
7619 goto error;
7620 }
7621
7622 outsize = PyUnicode_GET_LENGTH(rep);
7623 if (outsize != 1) {
7624 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7625 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7626 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7627 Py_DECREF(rep);
7628 goto error;
7629 }
7630 out = PyBytes_AS_STRING(*outbytes) + offset;
7631 }
7632 kind = PyUnicode_KIND(rep);
7633 data = PyUnicode_DATA(rep);
7634 for (i=0; i < outsize; i++) {
7635 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7636 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007637 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007638 encoding, unicode,
7639 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007640 "unable to encode error handler result to ASCII");
7641 Py_DECREF(rep);
7642 goto error;
7643 }
7644 *out = (unsigned char)ch;
7645 out++;
7646 }
7647 }
7648 Py_DECREF(rep);
7649 }
7650 /* write a NUL byte */
7651 *out = 0;
7652 outsize = out - PyBytes_AS_STRING(*outbytes);
7653 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7654 if (_PyBytes_Resize(outbytes, outsize) < 0)
7655 goto error;
7656 ret = 0;
7657
7658error:
7659 Py_XDECREF(encoding_obj);
7660 Py_XDECREF(errorHandler);
7661 Py_XDECREF(exc);
7662 return ret;
7663}
7664
Victor Stinner3a50e702011-10-18 21:21:00 +02007665static PyObject *
7666encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007667 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007668 const char *errors)
7669{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007670 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007671 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007672 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007673 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007674
Victor Stinner29dacf22015-01-26 16:41:32 +01007675 if (!PyUnicode_Check(unicode)) {
7676 PyErr_BadArgument();
7677 return NULL;
7678 }
7679
Benjamin Petersonbac79492012-01-14 13:34:47 -05007680 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007681 return NULL;
7682 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007683
Victor Stinner3a50e702011-10-18 21:21:00 +02007684 if (code_page < 0) {
7685 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7686 return NULL;
7687 }
7688
Martin v. Löwis3d325192011-11-04 18:23:06 +01007689 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007690 return PyBytes_FromStringAndSize(NULL, 0);
7691
Victor Stinner7581cef2011-11-03 22:32:33 +01007692 offset = 0;
7693 do
7694 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007695#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007696 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007697 chunks. */
7698 if (len > INT_MAX/2) {
7699 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007700 done = 0;
7701 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007702 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007703#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007704 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007705 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007706 done = 1;
7707 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007708
Victor Stinner76a31a62011-11-04 00:05:13 +01007709 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007710 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007711 errors);
7712 if (ret == -2)
7713 ret = encode_code_page_errors(code_page, &outbytes,
7714 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007715 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007716 if (ret < 0) {
7717 Py_XDECREF(outbytes);
7718 return NULL;
7719 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007720
Victor Stinner7581cef2011-11-03 22:32:33 +01007721 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007722 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007723 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007724
Victor Stinner3a50e702011-10-18 21:21:00 +02007725 return outbytes;
7726}
7727
7728PyObject *
7729PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7730 Py_ssize_t size,
7731 const char *errors)
7732{
Victor Stinner7581cef2011-11-03 22:32:33 +01007733 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007734 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007735 if (unicode == NULL)
7736 return NULL;
7737 res = encode_code_page(CP_ACP, unicode, errors);
7738 Py_DECREF(unicode);
7739 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007740}
7741
7742PyObject *
7743PyUnicode_EncodeCodePage(int code_page,
7744 PyObject *unicode,
7745 const char *errors)
7746{
Victor Stinner7581cef2011-11-03 22:32:33 +01007747 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007748}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007749
Alexander Belopolsky40018472011-02-26 01:02:56 +00007750PyObject *
7751PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007752{
Victor Stinner7581cef2011-11-03 22:32:33 +01007753 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007754}
7755
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007756#undef NEED_RETRY
7757
Steve Dowercc16be82016-09-08 10:35:16 -07007758#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007759
Guido van Rossumd57fd912000-03-10 22:53:23 +00007760/* --- Character Mapping Codec -------------------------------------------- */
7761
Victor Stinnerfb161b12013-04-18 01:44:27 +02007762static int
7763charmap_decode_string(const char *s,
7764 Py_ssize_t size,
7765 PyObject *mapping,
7766 const char *errors,
7767 _PyUnicodeWriter *writer)
7768{
7769 const char *starts = s;
7770 const char *e;
7771 Py_ssize_t startinpos, endinpos;
7772 PyObject *errorHandler = NULL, *exc = NULL;
7773 Py_ssize_t maplen;
7774 enum PyUnicode_Kind mapkind;
7775 void *mapdata;
7776 Py_UCS4 x;
7777 unsigned char ch;
7778
7779 if (PyUnicode_READY(mapping) == -1)
7780 return -1;
7781
7782 maplen = PyUnicode_GET_LENGTH(mapping);
7783 mapdata = PyUnicode_DATA(mapping);
7784 mapkind = PyUnicode_KIND(mapping);
7785
7786 e = s + size;
7787
7788 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7789 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7790 * is disabled in encoding aliases, latin1 is preferred because
7791 * its implementation is faster. */
7792 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7793 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7794 Py_UCS4 maxchar = writer->maxchar;
7795
7796 assert (writer->kind == PyUnicode_1BYTE_KIND);
7797 while (s < e) {
7798 ch = *s;
7799 x = mapdata_ucs1[ch];
7800 if (x > maxchar) {
7801 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7802 goto onError;
7803 maxchar = writer->maxchar;
7804 outdata = (Py_UCS1 *)writer->data;
7805 }
7806 outdata[writer->pos] = x;
7807 writer->pos++;
7808 ++s;
7809 }
7810 return 0;
7811 }
7812
7813 while (s < e) {
7814 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7815 enum PyUnicode_Kind outkind = writer->kind;
7816 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7817 if (outkind == PyUnicode_1BYTE_KIND) {
7818 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7819 Py_UCS4 maxchar = writer->maxchar;
7820 while (s < e) {
7821 ch = *s;
7822 x = mapdata_ucs2[ch];
7823 if (x > maxchar)
7824 goto Error;
7825 outdata[writer->pos] = x;
7826 writer->pos++;
7827 ++s;
7828 }
7829 break;
7830 }
7831 else if (outkind == PyUnicode_2BYTE_KIND) {
7832 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7833 while (s < e) {
7834 ch = *s;
7835 x = mapdata_ucs2[ch];
7836 if (x == 0xFFFE)
7837 goto Error;
7838 outdata[writer->pos] = x;
7839 writer->pos++;
7840 ++s;
7841 }
7842 break;
7843 }
7844 }
7845 ch = *s;
7846
7847 if (ch < maplen)
7848 x = PyUnicode_READ(mapkind, mapdata, ch);
7849 else
7850 x = 0xfffe; /* invalid value */
7851Error:
7852 if (x == 0xfffe)
7853 {
7854 /* undefined mapping */
7855 startinpos = s-starts;
7856 endinpos = startinpos+1;
7857 if (unicode_decode_call_errorhandler_writer(
7858 errors, &errorHandler,
7859 "charmap", "character maps to <undefined>",
7860 &starts, &e, &startinpos, &endinpos, &exc, &s,
7861 writer)) {
7862 goto onError;
7863 }
7864 continue;
7865 }
7866
7867 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7868 goto onError;
7869 ++s;
7870 }
7871 Py_XDECREF(errorHandler);
7872 Py_XDECREF(exc);
7873 return 0;
7874
7875onError:
7876 Py_XDECREF(errorHandler);
7877 Py_XDECREF(exc);
7878 return -1;
7879}
7880
7881static int
7882charmap_decode_mapping(const char *s,
7883 Py_ssize_t size,
7884 PyObject *mapping,
7885 const char *errors,
7886 _PyUnicodeWriter *writer)
7887{
7888 const char *starts = s;
7889 const char *e;
7890 Py_ssize_t startinpos, endinpos;
7891 PyObject *errorHandler = NULL, *exc = NULL;
7892 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007893 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007894
7895 e = s + size;
7896
7897 while (s < e) {
7898 ch = *s;
7899
7900 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7901 key = PyLong_FromLong((long)ch);
7902 if (key == NULL)
7903 goto onError;
7904
7905 item = PyObject_GetItem(mapping, key);
7906 Py_DECREF(key);
7907 if (item == NULL) {
7908 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7909 /* No mapping found means: mapping is undefined. */
7910 PyErr_Clear();
7911 goto Undefined;
7912 } else
7913 goto onError;
7914 }
7915
7916 /* Apply mapping */
7917 if (item == Py_None)
7918 goto Undefined;
7919 if (PyLong_Check(item)) {
7920 long value = PyLong_AS_LONG(item);
7921 if (value == 0xFFFE)
7922 goto Undefined;
7923 if (value < 0 || value > MAX_UNICODE) {
7924 PyErr_Format(PyExc_TypeError,
7925 "character mapping must be in range(0x%lx)",
7926 (unsigned long)MAX_UNICODE + 1);
7927 goto onError;
7928 }
7929
7930 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7931 goto onError;
7932 }
7933 else if (PyUnicode_Check(item)) {
7934 if (PyUnicode_READY(item) == -1)
7935 goto onError;
7936 if (PyUnicode_GET_LENGTH(item) == 1) {
7937 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7938 if (value == 0xFFFE)
7939 goto Undefined;
7940 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7941 goto onError;
7942 }
7943 else {
7944 writer->overallocate = 1;
7945 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7946 goto onError;
7947 }
7948 }
7949 else {
7950 /* wrong return value */
7951 PyErr_SetString(PyExc_TypeError,
7952 "character mapping must return integer, None or str");
7953 goto onError;
7954 }
7955 Py_CLEAR(item);
7956 ++s;
7957 continue;
7958
7959Undefined:
7960 /* undefined mapping */
7961 Py_CLEAR(item);
7962 startinpos = s-starts;
7963 endinpos = startinpos+1;
7964 if (unicode_decode_call_errorhandler_writer(
7965 errors, &errorHandler,
7966 "charmap", "character maps to <undefined>",
7967 &starts, &e, &startinpos, &endinpos, &exc, &s,
7968 writer)) {
7969 goto onError;
7970 }
7971 }
7972 Py_XDECREF(errorHandler);
7973 Py_XDECREF(exc);
7974 return 0;
7975
7976onError:
7977 Py_XDECREF(item);
7978 Py_XDECREF(errorHandler);
7979 Py_XDECREF(exc);
7980 return -1;
7981}
7982
Alexander Belopolsky40018472011-02-26 01:02:56 +00007983PyObject *
7984PyUnicode_DecodeCharmap(const char *s,
7985 Py_ssize_t size,
7986 PyObject *mapping,
7987 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007988{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007989 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007990
Guido van Rossumd57fd912000-03-10 22:53:23 +00007991 /* Default to Latin-1 */
7992 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007994
Guido van Rossumd57fd912000-03-10 22:53:23 +00007995 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007996 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007997 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007998 writer.min_length = size;
7999 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008000 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008001
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008002 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008003 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8004 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008005 }
8006 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008007 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8008 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008009 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008010 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008011
Benjamin Peterson29060642009-01-31 22:14:21 +00008012 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008013 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008014 return NULL;
8015}
8016
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017/* Charmap encoding: the lookup table */
8018
Alexander Belopolsky40018472011-02-26 01:02:56 +00008019struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 PyObject_HEAD
8021 unsigned char level1[32];
8022 int count2, count3;
8023 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024};
8025
8026static PyObject*
8027encoding_map_size(PyObject *obj, PyObject* args)
8028{
8029 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008030 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032}
8033
8034static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008035 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 PyDoc_STR("Return the size (in bytes) of this object") },
8037 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008038};
8039
8040static void
8041encoding_map_dealloc(PyObject* o)
8042{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008043 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008044}
8045
8046static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008047 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008048 "EncodingMap", /*tp_name*/
8049 sizeof(struct encoding_map), /*tp_basicsize*/
8050 0, /*tp_itemsize*/
8051 /* methods */
8052 encoding_map_dealloc, /*tp_dealloc*/
8053 0, /*tp_print*/
8054 0, /*tp_getattr*/
8055 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008056 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 0, /*tp_repr*/
8058 0, /*tp_as_number*/
8059 0, /*tp_as_sequence*/
8060 0, /*tp_as_mapping*/
8061 0, /*tp_hash*/
8062 0, /*tp_call*/
8063 0, /*tp_str*/
8064 0, /*tp_getattro*/
8065 0, /*tp_setattro*/
8066 0, /*tp_as_buffer*/
8067 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8068 0, /*tp_doc*/
8069 0, /*tp_traverse*/
8070 0, /*tp_clear*/
8071 0, /*tp_richcompare*/
8072 0, /*tp_weaklistoffset*/
8073 0, /*tp_iter*/
8074 0, /*tp_iternext*/
8075 encoding_map_methods, /*tp_methods*/
8076 0, /*tp_members*/
8077 0, /*tp_getset*/
8078 0, /*tp_base*/
8079 0, /*tp_dict*/
8080 0, /*tp_descr_get*/
8081 0, /*tp_descr_set*/
8082 0, /*tp_dictoffset*/
8083 0, /*tp_init*/
8084 0, /*tp_alloc*/
8085 0, /*tp_new*/
8086 0, /*tp_free*/
8087 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088};
8089
8090PyObject*
8091PyUnicode_BuildEncodingMap(PyObject* string)
8092{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093 PyObject *result;
8094 struct encoding_map *mresult;
8095 int i;
8096 int need_dict = 0;
8097 unsigned char level1[32];
8098 unsigned char level2[512];
8099 unsigned char *mlevel1, *mlevel2, *mlevel3;
8100 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008101 int kind;
8102 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008103 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008105
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008106 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107 PyErr_BadArgument();
8108 return NULL;
8109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008110 kind = PyUnicode_KIND(string);
8111 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008112 length = PyUnicode_GET_LENGTH(string);
8113 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114 memset(level1, 0xFF, sizeof level1);
8115 memset(level2, 0xFF, sizeof level2);
8116
8117 /* If there isn't a one-to-one mapping of NULL to \0,
8118 or if there are non-BMP characters, we need to use
8119 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008120 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008124 ch = PyUnicode_READ(kind, data, i);
8125 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 need_dict = 1;
8127 break;
8128 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008129 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 /* unmapped character */
8131 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008132 l1 = ch >> 11;
8133 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 if (level1[l1] == 0xFF)
8135 level1[l1] = count2++;
8136 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008138 }
8139
8140 if (count2 >= 0xFF || count3 >= 0xFF)
8141 need_dict = 1;
8142
8143 if (need_dict) {
8144 PyObject *result = PyDict_New();
8145 PyObject *key, *value;
8146 if (!result)
8147 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008148 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008149 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008150 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151 if (!key || !value)
8152 goto failed1;
8153 if (PyDict_SetItem(result, key, value) == -1)
8154 goto failed1;
8155 Py_DECREF(key);
8156 Py_DECREF(value);
8157 }
8158 return result;
8159 failed1:
8160 Py_XDECREF(key);
8161 Py_XDECREF(value);
8162 Py_DECREF(result);
8163 return NULL;
8164 }
8165
8166 /* Create a three-level trie */
8167 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8168 16*count2 + 128*count3 - 1);
8169 if (!result)
8170 return PyErr_NoMemory();
8171 PyObject_Init(result, &EncodingMapType);
8172 mresult = (struct encoding_map*)result;
8173 mresult->count2 = count2;
8174 mresult->count3 = count3;
8175 mlevel1 = mresult->level1;
8176 mlevel2 = mresult->level23;
8177 mlevel3 = mresult->level23 + 16*count2;
8178 memcpy(mlevel1, level1, 32);
8179 memset(mlevel2, 0xFF, 16*count2);
8180 memset(mlevel3, 0, 128*count3);
8181 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008182 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008183 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008184 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8185 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008186 /* unmapped character */
8187 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008188 o1 = ch>>11;
8189 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190 i2 = 16*mlevel1[o1] + o2;
8191 if (mlevel2[i2] == 0xFF)
8192 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008193 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194 i3 = 128*mlevel2[i2] + o3;
8195 mlevel3[i3] = i;
8196 }
8197 return result;
8198}
8199
8200static int
Victor Stinner22168992011-11-20 17:09:18 +01008201encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008202{
8203 struct encoding_map *map = (struct encoding_map*)mapping;
8204 int l1 = c>>11;
8205 int l2 = (c>>7) & 0xF;
8206 int l3 = c & 0x7F;
8207 int i;
8208
Victor Stinner22168992011-11-20 17:09:18 +01008209 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008211 if (c == 0)
8212 return 0;
8213 /* level 1*/
8214 i = map->level1[l1];
8215 if (i == 0xFF) {
8216 return -1;
8217 }
8218 /* level 2*/
8219 i = map->level23[16*i+l2];
8220 if (i == 0xFF) {
8221 return -1;
8222 }
8223 /* level 3 */
8224 i = map->level23[16*map->count2 + 128*i + l3];
8225 if (i == 0) {
8226 return -1;
8227 }
8228 return i;
8229}
8230
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231/* Lookup the character ch in the mapping. If the character
8232 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008233 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008234static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008235charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008236{
Christian Heimes217cfd12007-12-02 14:31:20 +00008237 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 PyObject *x;
8239
8240 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 x = PyObject_GetItem(mapping, w);
8243 Py_DECREF(w);
8244 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8246 /* No mapping found means: mapping is undefined. */
8247 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008248 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 } else
8250 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008252 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008254 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 long value = PyLong_AS_LONG(x);
8256 if (value < 0 || value > 255) {
8257 PyErr_SetString(PyExc_TypeError,
8258 "character mapping must be in range(256)");
8259 Py_DECREF(x);
8260 return NULL;
8261 }
8262 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008264 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008266 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 /* wrong return value */
8268 PyErr_Format(PyExc_TypeError,
8269 "character mapping must return integer, bytes or None, not %.400s",
8270 x->ob_type->tp_name);
8271 Py_DECREF(x);
8272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008273 }
8274}
8275
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008276static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008277charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008278{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008279 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8280 /* exponentially overallocate to minimize reallocations */
8281 if (requiredsize < 2*outsize)
8282 requiredsize = 2*outsize;
8283 if (_PyBytes_Resize(outobj, requiredsize))
8284 return -1;
8285 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008286}
8287
Benjamin Peterson14339b62009-01-31 16:36:08 +00008288typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008290} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008292 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 space is available. Return a new reference to the object that
8294 was put in the output buffer, or Py_None, if the mapping was undefined
8295 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008296 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008297static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008298charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008299 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008301 PyObject *rep;
8302 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008303 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304
Christian Heimes90aa7642007-12-19 02:45:37 +00008305 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008306 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008308 if (res == -1)
8309 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 if (outsize<requiredsize)
8311 if (charmapencode_resize(outobj, outpos, requiredsize))
8312 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008313 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 outstart[(*outpos)++] = (char)res;
8315 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008316 }
8317
8318 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008321 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 Py_DECREF(rep);
8323 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008324 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 if (PyLong_Check(rep)) {
8326 Py_ssize_t requiredsize = *outpos+1;
8327 if (outsize<requiredsize)
8328 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8329 Py_DECREF(rep);
8330 return enc_EXCEPTION;
8331 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008332 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008334 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 else {
8336 const char *repchars = PyBytes_AS_STRING(rep);
8337 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8338 Py_ssize_t requiredsize = *outpos+repsize;
8339 if (outsize<requiredsize)
8340 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8341 Py_DECREF(rep);
8342 return enc_EXCEPTION;
8343 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008344 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 memcpy(outstart + *outpos, repchars, repsize);
8346 *outpos += repsize;
8347 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008349 Py_DECREF(rep);
8350 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351}
8352
8353/* handle an error in PyUnicode_EncodeCharmap
8354 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008355static int
8356charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008357 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008359 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008360 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361{
8362 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008363 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008364 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008365 enum PyUnicode_Kind kind;
8366 void *data;
8367 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008369 Py_ssize_t collstartpos = *inpos;
8370 Py_ssize_t collendpos = *inpos+1;
8371 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008372 const char *encoding = "charmap";
8373 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008374 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008375 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008376 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377
Benjamin Petersonbac79492012-01-14 13:34:47 -05008378 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008379 return -1;
8380 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 /* find all unencodable characters */
8382 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008383 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008384 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008385 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008386 val = encoding_map_lookup(ch, mapping);
8387 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 break;
8389 ++collendpos;
8390 continue;
8391 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008392
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008393 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8394 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 if (rep==NULL)
8396 return -1;
8397 else if (rep!=Py_None) {
8398 Py_DECREF(rep);
8399 break;
8400 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008401 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 }
8404 /* cache callback name lookup
8405 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008406 if (*error_handler == _Py_ERROR_UNKNOWN)
8407 *error_handler = get_error_handler(errors);
8408
8409 switch (*error_handler) {
8410 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008411 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008412 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008413
8414 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008415 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 x = charmapencode_output('?', mapping, res, respos);
8417 if (x==enc_EXCEPTION) {
8418 return -1;
8419 }
8420 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008421 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 return -1;
8423 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008424 }
8425 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008426 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008427 *inpos = collendpos;
8428 break;
Victor Stinner50149202015-09-22 00:26:54 +02008429
8430 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008431 /* generate replacement (temporarily (mis)uses p) */
8432 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 char buffer[2+29+1+1];
8434 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008435 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 for (cp = buffer; *cp; ++cp) {
8437 x = charmapencode_output(*cp, mapping, res, respos);
8438 if (x==enc_EXCEPTION)
8439 return -1;
8440 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008441 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 return -1;
8443 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008444 }
8445 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008446 *inpos = collendpos;
8447 break;
Victor Stinner50149202015-09-22 00:26:54 +02008448
Benjamin Peterson14339b62009-01-31 16:36:08 +00008449 default:
Victor Stinner50149202015-09-22 00:26:54 +02008450 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008451 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008453 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008455 if (PyBytes_Check(repunicode)) {
8456 /* Directly copy bytes result to output. */
8457 Py_ssize_t outsize = PyBytes_Size(*res);
8458 Py_ssize_t requiredsize;
8459 repsize = PyBytes_Size(repunicode);
8460 requiredsize = *respos + repsize;
8461 if (requiredsize > outsize)
8462 /* Make room for all additional bytes. */
8463 if (charmapencode_resize(res, respos, requiredsize)) {
8464 Py_DECREF(repunicode);
8465 return -1;
8466 }
8467 memcpy(PyBytes_AsString(*res) + *respos,
8468 PyBytes_AsString(repunicode), repsize);
8469 *respos += repsize;
8470 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008471 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008472 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008473 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008474 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008475 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008476 Py_DECREF(repunicode);
8477 return -1;
8478 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008479 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008480 data = PyUnicode_DATA(repunicode);
8481 kind = PyUnicode_KIND(repunicode);
8482 for (index = 0; index < repsize; index++) {
8483 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8484 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008486 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 return -1;
8488 }
8489 else if (x==enc_FAILED) {
8490 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008491 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 return -1;
8493 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008494 }
8495 *inpos = newpos;
8496 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497 }
8498 return 0;
8499}
8500
Alexander Belopolsky40018472011-02-26 01:02:56 +00008501PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008502_PyUnicode_EncodeCharmap(PyObject *unicode,
8503 PyObject *mapping,
8504 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008505{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 /* output object */
8507 PyObject *res = NULL;
8508 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008509 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008510 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008512 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008513 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008515 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008516 void *data;
8517 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518
Benjamin Petersonbac79492012-01-14 13:34:47 -05008519 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008520 return NULL;
8521 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008522 data = PyUnicode_DATA(unicode);
8523 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008524
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525 /* Default to Latin-1 */
8526 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008527 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 /* allocate enough for a simple encoding without
8530 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008531 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 if (res == NULL)
8533 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008534 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008536
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008538 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008540 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 if (x==enc_EXCEPTION) /* error */
8542 goto onError;
8543 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008544 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008546 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 &res, &respos)) {
8548 goto onError;
8549 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008550 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 else
8552 /* done with this character => adjust input position */
8553 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008554 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008557 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008558 if (_PyBytes_Resize(&res, respos) < 0)
8559 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008560
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008562 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 return res;
8564
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 Py_XDECREF(res);
8567 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008568 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569 return NULL;
8570}
8571
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008572/* Deprecated */
8573PyObject *
8574PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8575 Py_ssize_t size,
8576 PyObject *mapping,
8577 const char *errors)
8578{
8579 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008580 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008581 if (unicode == NULL)
8582 return NULL;
8583 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8584 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008585 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008586}
8587
Alexander Belopolsky40018472011-02-26 01:02:56 +00008588PyObject *
8589PyUnicode_AsCharmapString(PyObject *unicode,
8590 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008591{
8592 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 PyErr_BadArgument();
8594 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008595 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008596 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597}
8598
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008599/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008600static void
8601make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008603 Py_ssize_t startpos, Py_ssize_t endpos,
8604 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008606 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 *exceptionObject = _PyUnicodeTranslateError_Create(
8608 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008609 }
8610 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8612 goto onError;
8613 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8614 goto onError;
8615 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8616 goto onError;
8617 return;
8618 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008619 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620 }
8621}
8622
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623/* error handling callback helper:
8624 build arguments, call the callback and check the arguments,
8625 put the result into newpos and return the replacement string, which
8626 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008627static PyObject *
8628unicode_translate_call_errorhandler(const char *errors,
8629 PyObject **errorHandler,
8630 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008632 Py_ssize_t startpos, Py_ssize_t endpos,
8633 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008635 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008637 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 PyObject *restuple;
8639 PyObject *resunicode;
8640
8641 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008645 }
8646
8647 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008651
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008652 restuple = PyObject_CallFunctionObjArgs(
8653 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008656 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008657 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 Py_DECREF(restuple);
8659 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008661 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 &resunicode, &i_newpos)) {
8663 Py_DECREF(restuple);
8664 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008666 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008668 else
8669 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008671 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 Py_DECREF(restuple);
8673 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008674 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 Py_INCREF(resunicode);
8676 Py_DECREF(restuple);
8677 return resunicode;
8678}
8679
8680/* Lookup the character ch in the mapping and put the result in result,
8681 which must be decrefed by the caller.
8682 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008683static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685{
Christian Heimes217cfd12007-12-02 14:31:20 +00008686 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 PyObject *x;
8688
8689 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 x = PyObject_GetItem(mapping, w);
8692 Py_DECREF(w);
8693 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8695 /* No mapping found means: use 1:1 mapping. */
8696 PyErr_Clear();
8697 *result = NULL;
8698 return 0;
8699 } else
8700 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008701 }
8702 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 *result = x;
8704 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008705 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008706 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008708 if (value < 0 || value > MAX_UNICODE) {
8709 PyErr_Format(PyExc_ValueError,
8710 "character mapping must be in range(0x%x)",
8711 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 Py_DECREF(x);
8713 return -1;
8714 }
8715 *result = x;
8716 return 0;
8717 }
8718 else if (PyUnicode_Check(x)) {
8719 *result = x;
8720 return 0;
8721 }
8722 else {
8723 /* wrong return value */
8724 PyErr_SetString(PyExc_TypeError,
8725 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008726 Py_DECREF(x);
8727 return -1;
8728 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008729}
Victor Stinner1194ea02014-04-04 19:37:40 +02008730
8731/* lookup the character, write the result into the writer.
8732 Return 1 if the result was written into the writer, return 0 if the mapping
8733 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008734static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008735charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8736 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008737{
Victor Stinner1194ea02014-04-04 19:37:40 +02008738 PyObject *item;
8739
8740 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008742
8743 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008745 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008748 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008749 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008750
8751 if (item == Py_None) {
8752 Py_DECREF(item);
8753 return 0;
8754 }
8755
8756 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008757 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8758 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8759 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008760 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8761 Py_DECREF(item);
8762 return -1;
8763 }
8764 Py_DECREF(item);
8765 return 1;
8766 }
8767
8768 if (!PyUnicode_Check(item)) {
8769 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008771 }
8772
8773 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8774 Py_DECREF(item);
8775 return -1;
8776 }
8777
8778 Py_DECREF(item);
8779 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008780}
8781
Victor Stinner89a76ab2014-04-05 11:44:04 +02008782static int
8783unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8784 Py_UCS1 *translate)
8785{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008786 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008787 int ret = 0;
8788
Victor Stinner89a76ab2014-04-05 11:44:04 +02008789 if (charmaptranslate_lookup(ch, mapping, &item)) {
8790 return -1;
8791 }
8792
8793 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008794 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008795 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008796 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008797 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008798 /* not found => default to 1:1 mapping */
8799 translate[ch] = ch;
8800 return 1;
8801 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008802 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008803 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008804 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8805 used it */
8806 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008807 /* invalid character or character outside ASCII:
8808 skip the fast translate */
8809 goto exit;
8810 }
8811 translate[ch] = (Py_UCS1)replace;
8812 }
8813 else if (PyUnicode_Check(item)) {
8814 Py_UCS4 replace;
8815
8816 if (PyUnicode_READY(item) == -1) {
8817 Py_DECREF(item);
8818 return -1;
8819 }
8820 if (PyUnicode_GET_LENGTH(item) != 1)
8821 goto exit;
8822
8823 replace = PyUnicode_READ_CHAR(item, 0);
8824 if (replace > 127)
8825 goto exit;
8826 translate[ch] = (Py_UCS1)replace;
8827 }
8828 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008829 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008830 goto exit;
8831 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008832 ret = 1;
8833
Benjamin Peterson1365de72014-04-07 20:15:41 -04008834 exit:
8835 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008836 return ret;
8837}
8838
8839/* Fast path for ascii => ascii translation. Return 1 if the whole string
8840 was translated into writer, return 0 if the input string was partially
8841 translated into writer, raise an exception and return -1 on error. */
8842static int
8843unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008844 _PyUnicodeWriter *writer, int ignore,
8845 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008846{
Victor Stinner872b2912014-04-05 14:27:07 +02008847 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008848 Py_ssize_t len;
8849 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008850 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851
Victor Stinner89a76ab2014-04-05 11:44:04 +02008852 len = PyUnicode_GET_LENGTH(input);
8853
Victor Stinner872b2912014-04-05 14:27:07 +02008854 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855
8856 in = PyUnicode_1BYTE_DATA(input);
8857 end = in + len;
8858
8859 assert(PyUnicode_IS_ASCII(writer->buffer));
8860 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8861 out = PyUnicode_1BYTE_DATA(writer->buffer);
8862
Victor Stinner872b2912014-04-05 14:27:07 +02008863 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008864 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008865 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008866 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008867 int translate = unicode_fast_translate_lookup(mapping, ch,
8868 ascii_table);
8869 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008870 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008871 if (translate == 0)
8872 goto exit;
8873 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008874 }
Victor Stinner872b2912014-04-05 14:27:07 +02008875 if (ch2 == 0xfe) {
8876 if (ignore)
8877 continue;
8878 goto exit;
8879 }
8880 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008881 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008882 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008883 }
Victor Stinner872b2912014-04-05 14:27:07 +02008884 res = 1;
8885
8886exit:
8887 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008888 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008889 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008890}
8891
Victor Stinner3222da22015-10-01 22:07:32 +02008892static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008893_PyUnicode_TranslateCharmap(PyObject *input,
8894 PyObject *mapping,
8895 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008898 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899 Py_ssize_t size, i;
8900 int kind;
8901 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008902 _PyUnicodeWriter writer;
8903 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008904 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008905 PyObject *errorHandler = NULL;
8906 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008907 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008908 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008909
Guido van Rossumd57fd912000-03-10 22:53:23 +00008910 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008911 PyErr_BadArgument();
8912 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008913 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915 if (PyUnicode_READY(input) == -1)
8916 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008917 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008918 kind = PyUnicode_KIND(input);
8919 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008921 if (size == 0)
8922 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008924 /* allocate enough for a simple 1:1 translation without
8925 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008926 _PyUnicodeWriter_Init(&writer);
8927 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008929
Victor Stinner872b2912014-04-05 14:27:07 +02008930 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8931
Victor Stinner33798672016-03-01 21:59:58 +01008932 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008933 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008934 if (PyUnicode_IS_ASCII(input)) {
8935 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8936 if (res < 0) {
8937 _PyUnicodeWriter_Dealloc(&writer);
8938 return NULL;
8939 }
8940 if (res == 1)
8941 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008942 }
Victor Stinner33798672016-03-01 21:59:58 +01008943 else {
8944 i = 0;
8945 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008947 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008948 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008949 int translate;
8950 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8951 Py_ssize_t newpos;
8952 /* startpos for collecting untranslatable chars */
8953 Py_ssize_t collstart;
8954 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008955 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008956
Victor Stinner1194ea02014-04-04 19:37:40 +02008957 ch = PyUnicode_READ(kind, data, i);
8958 translate = charmaptranslate_output(ch, mapping, &writer);
8959 if (translate < 0)
8960 goto onError;
8961
8962 if (translate != 0) {
8963 /* it worked => adjust input pointer */
8964 ++i;
8965 continue;
8966 }
8967
8968 /* untranslatable character */
8969 collstart = i;
8970 collend = i+1;
8971
8972 /* find all untranslatable characters */
8973 while (collend < size) {
8974 PyObject *x;
8975 ch = PyUnicode_READ(kind, data, collend);
8976 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008977 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008978 Py_XDECREF(x);
8979 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008980 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008981 ++collend;
8982 }
8983
8984 if (ignore) {
8985 i = collend;
8986 }
8987 else {
8988 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8989 reason, input, &exc,
8990 collstart, collend, &newpos);
8991 if (repunicode == NULL)
8992 goto onError;
8993 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008994 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008995 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008996 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008997 Py_DECREF(repunicode);
8998 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008999 }
9000 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009001 Py_XDECREF(exc);
9002 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009003 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004
Benjamin Peterson29060642009-01-31 22:14:21 +00009005 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009006 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009007 Py_XDECREF(exc);
9008 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009 return NULL;
9010}
9011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012/* Deprecated. Use PyUnicode_Translate instead. */
9013PyObject *
9014PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9015 Py_ssize_t size,
9016 PyObject *mapping,
9017 const char *errors)
9018{
Christian Heimes5f520f42012-09-11 14:03:25 +02009019 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009020 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021 if (!unicode)
9022 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009023 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9024 Py_DECREF(unicode);
9025 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026}
9027
Alexander Belopolsky40018472011-02-26 01:02:56 +00009028PyObject *
9029PyUnicode_Translate(PyObject *str,
9030 PyObject *mapping,
9031 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009032{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009033 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009034 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009035 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036}
Tim Petersced69f82003-09-16 20:30:58 +00009037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038PyObject *
9039_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9040{
9041 if (!PyUnicode_Check(unicode)) {
9042 PyErr_BadInternalCall();
9043 return NULL;
9044 }
9045 if (PyUnicode_READY(unicode) == -1)
9046 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009047 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009048 /* If the string is already ASCII, just return the same string */
9049 Py_INCREF(unicode);
9050 return unicode;
9051 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009052
9053 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9054 PyObject *result = PyUnicode_New(len, 127);
9055 if (result == NULL) {
9056 return NULL;
9057 }
9058
9059 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9060 int kind = PyUnicode_KIND(unicode);
9061 const void *data = PyUnicode_DATA(unicode);
9062 Py_ssize_t i;
9063 for (i = 0; i < len; ++i) {
9064 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9065 if (ch < 127) {
9066 out[i] = ch;
9067 }
9068 else if (Py_UNICODE_ISSPACE(ch)) {
9069 out[i] = ' ';
9070 }
9071 else {
9072 int decimal = Py_UNICODE_TODECIMAL(ch);
9073 if (decimal < 0) {
9074 out[i] = '?';
9075 _PyUnicode_LENGTH(result) = i + 1;
9076 break;
9077 }
9078 out[i] = '0' + decimal;
9079 }
9080 }
9081
9082 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083}
9084
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009085PyObject *
9086PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9087 Py_ssize_t length)
9088{
Victor Stinnerf0124502011-11-21 23:12:56 +01009089 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009090 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009091 Py_UCS4 maxchar;
9092 enum PyUnicode_Kind kind;
9093 void *data;
9094
Victor Stinner99d7ad02012-02-22 13:37:39 +01009095 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009096 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009097 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009098 if (ch > 127) {
9099 int decimal = Py_UNICODE_TODECIMAL(ch);
9100 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009101 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009102 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009103 }
9104 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009105
9106 /* Copy to a new string */
9107 decimal = PyUnicode_New(length, maxchar);
9108 if (decimal == NULL)
9109 return decimal;
9110 kind = PyUnicode_KIND(decimal);
9111 data = PyUnicode_DATA(decimal);
9112 /* Iterate over code points */
9113 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009114 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009115 if (ch > 127) {
9116 int decimal = Py_UNICODE_TODECIMAL(ch);
9117 if (decimal >= 0)
9118 ch = '0' + decimal;
9119 }
9120 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009122 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009123}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009124/* --- Decimal Encoder ---------------------------------------------------- */
9125
Alexander Belopolsky40018472011-02-26 01:02:56 +00009126int
9127PyUnicode_EncodeDecimal(Py_UNICODE *s,
9128 Py_ssize_t length,
9129 char *output,
9130 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009131{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009132 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009133 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009134 enum PyUnicode_Kind kind;
9135 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009136
9137 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009138 PyErr_BadArgument();
9139 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009140 }
9141
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009142 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009143 if (unicode == NULL)
9144 return -1;
9145
Victor Stinner42bf7752011-11-21 22:52:58 +01009146 kind = PyUnicode_KIND(unicode);
9147 data = PyUnicode_DATA(unicode);
9148
Victor Stinnerb84d7232011-11-22 01:50:07 +01009149 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009150 PyObject *exc;
9151 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009152 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009153 Py_ssize_t startpos;
9154
9155 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009156
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009158 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009159 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009160 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009161 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009162 decimal = Py_UNICODE_TODECIMAL(ch);
9163 if (decimal >= 0) {
9164 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009165 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 continue;
9167 }
9168 if (0 < ch && ch < 256) {
9169 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009170 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 continue;
9172 }
Victor Stinner6345be92011-11-25 20:09:01 +01009173
Victor Stinner42bf7752011-11-21 22:52:58 +01009174 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009175 exc = NULL;
9176 raise_encode_exception(&exc, "decimal", unicode,
9177 startpos, startpos+1,
9178 "invalid decimal Unicode string");
9179 Py_XDECREF(exc);
9180 Py_DECREF(unicode);
9181 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009182 }
9183 /* 0-terminate the output string */
9184 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009185 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009186 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009187}
9188
Guido van Rossumd57fd912000-03-10 22:53:23 +00009189/* --- Helpers ------------------------------------------------------------ */
9190
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009191/* helper macro to fixup start/end slice values */
9192#define ADJUST_INDICES(start, end, len) \
9193 if (end > len) \
9194 end = len; \
9195 else if (end < 0) { \
9196 end += len; \
9197 if (end < 0) \
9198 end = 0; \
9199 } \
9200 if (start < 0) { \
9201 start += len; \
9202 if (start < 0) \
9203 start = 0; \
9204 }
9205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009207any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009209 Py_ssize_t end,
9210 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009212 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213 void *buf1, *buf2;
9214 Py_ssize_t len1, len2, result;
9215
9216 kind1 = PyUnicode_KIND(s1);
9217 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009218 if (kind1 < kind2)
9219 return -1;
9220
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009221 len1 = PyUnicode_GET_LENGTH(s1);
9222 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009223 ADJUST_INDICES(start, end, len1);
9224 if (end - start < len2)
9225 return -1;
9226
9227 buf1 = PyUnicode_DATA(s1);
9228 buf2 = PyUnicode_DATA(s2);
9229 if (len2 == 1) {
9230 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9231 result = findchar((const char *)buf1 + kind1*start,
9232 kind1, end - start, ch, direction);
9233 if (result == -1)
9234 return -1;
9235 else
9236 return start + result;
9237 }
9238
9239 if (kind2 != kind1) {
9240 buf2 = _PyUnicode_AsKind(s2, kind1);
9241 if (!buf2)
9242 return -2;
9243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244
Victor Stinner794d5672011-10-10 03:21:36 +02009245 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009246 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009247 case PyUnicode_1BYTE_KIND:
9248 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9249 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9250 else
9251 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9252 break;
9253 case PyUnicode_2BYTE_KIND:
9254 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9255 break;
9256 case PyUnicode_4BYTE_KIND:
9257 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9258 break;
9259 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009260 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009261 }
9262 }
9263 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009264 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009265 case PyUnicode_1BYTE_KIND:
9266 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9267 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9268 else
9269 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9270 break;
9271 case PyUnicode_2BYTE_KIND:
9272 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9273 break;
9274 case PyUnicode_4BYTE_KIND:
9275 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9276 break;
9277 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009278 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009279 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 }
9281
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009282 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 PyMem_Free(buf2);
9284
9285 return result;
9286}
9287
9288Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009289_PyUnicode_InsertThousandsGrouping(
9290 PyObject *unicode, Py_ssize_t index,
9291 Py_ssize_t n_buffer,
9292 void *digits, Py_ssize_t n_digits,
9293 Py_ssize_t min_width,
9294 const char *grouping, PyObject *thousands_sep,
9295 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296{
Victor Stinner41a863c2012-02-24 00:37:51 +01009297 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009298 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009299 Py_ssize_t thousands_sep_len;
9300 Py_ssize_t len;
9301
9302 if (unicode != NULL) {
9303 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009304 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009305 }
9306 else {
9307 kind = PyUnicode_1BYTE_KIND;
9308 data = NULL;
9309 }
9310 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9311 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9312 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9313 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009314 if (thousands_sep_kind < kind) {
9315 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9316 if (!thousands_sep_data)
9317 return -1;
9318 }
9319 else {
9320 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9321 if (!data)
9322 return -1;
9323 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009324 }
9325
Benjamin Petersonead6b532011-12-20 17:23:42 -06009326 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009328 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009329 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009330 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009331 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009332 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009333 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009334 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009335 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009336 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009337 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009338 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009339 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009341 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009342 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009343 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009344 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009346 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009347 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009348 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009349 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009350 break;
9351 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009352 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009354 if (unicode != NULL && thousands_sep_kind != kind) {
9355 if (thousands_sep_kind < kind)
9356 PyMem_Free(thousands_sep_data);
9357 else
9358 PyMem_Free(data);
9359 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009360 if (unicode == NULL) {
9361 *maxchar = 127;
9362 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009363 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009364 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009365 }
9366 }
9367 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368}
9369
9370
Alexander Belopolsky40018472011-02-26 01:02:56 +00009371Py_ssize_t
9372PyUnicode_Count(PyObject *str,
9373 PyObject *substr,
9374 Py_ssize_t start,
9375 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009377 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009378 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 void *buf1 = NULL, *buf2 = NULL;
9380 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009381
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009382 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009384
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009385 kind1 = PyUnicode_KIND(str);
9386 kind2 = PyUnicode_KIND(substr);
9387 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009388 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009389
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009390 len1 = PyUnicode_GET_LENGTH(str);
9391 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009393 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009394 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009395
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009396 buf1 = PyUnicode_DATA(str);
9397 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009398 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009399 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009400 if (!buf2)
9401 goto onError;
9402 }
9403
9404 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009406 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009407 result = asciilib_count(
9408 ((Py_UCS1*)buf1) + start, end - start,
9409 buf2, len2, PY_SSIZE_T_MAX
9410 );
9411 else
9412 result = ucs1lib_count(
9413 ((Py_UCS1*)buf1) + start, end - start,
9414 buf2, len2, PY_SSIZE_T_MAX
9415 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 break;
9417 case PyUnicode_2BYTE_KIND:
9418 result = ucs2lib_count(
9419 ((Py_UCS2*)buf1) + start, end - start,
9420 buf2, len2, PY_SSIZE_T_MAX
9421 );
9422 break;
9423 case PyUnicode_4BYTE_KIND:
9424 result = ucs4lib_count(
9425 ((Py_UCS4*)buf1) + start, end - start,
9426 buf2, len2, PY_SSIZE_T_MAX
9427 );
9428 break;
9429 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009430 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009432
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009433 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 PyMem_Free(buf2);
9435
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009438 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 PyMem_Free(buf2);
9440 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441}
9442
Alexander Belopolsky40018472011-02-26 01:02:56 +00009443Py_ssize_t
9444PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009445 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009446 Py_ssize_t start,
9447 Py_ssize_t end,
9448 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009449{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009450 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009451 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009452
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009453 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454}
9455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456Py_ssize_t
9457PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9458 Py_ssize_t start, Py_ssize_t end,
9459 int direction)
9460{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009462 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 if (PyUnicode_READY(str) == -1)
9464 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009465 len = PyUnicode_GET_LENGTH(str);
9466 ADJUST_INDICES(start, end, len);
9467 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009468 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009470 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9471 kind, end-start, ch, direction);
9472 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009474 else
9475 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476}
9477
Alexander Belopolsky40018472011-02-26 01:02:56 +00009478static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009479tailmatch(PyObject *self,
9480 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009481 Py_ssize_t start,
9482 Py_ssize_t end,
9483 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 int kind_self;
9486 int kind_sub;
9487 void *data_self;
9488 void *data_sub;
9489 Py_ssize_t offset;
9490 Py_ssize_t i;
9491 Py_ssize_t end_sub;
9492
9493 if (PyUnicode_READY(self) == -1 ||
9494 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009495 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9498 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009500 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009502 if (PyUnicode_GET_LENGTH(substring) == 0)
9503 return 1;
9504
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505 kind_self = PyUnicode_KIND(self);
9506 data_self = PyUnicode_DATA(self);
9507 kind_sub = PyUnicode_KIND(substring);
9508 data_sub = PyUnicode_DATA(substring);
9509 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9510
9511 if (direction > 0)
9512 offset = end;
9513 else
9514 offset = start;
9515
9516 if (PyUnicode_READ(kind_self, data_self, offset) ==
9517 PyUnicode_READ(kind_sub, data_sub, 0) &&
9518 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9519 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9520 /* If both are of the same kind, memcmp is sufficient */
9521 if (kind_self == kind_sub) {
9522 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009523 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524 data_sub,
9525 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009526 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009528 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 else {
9530 /* We do not need to compare 0 and len(substring)-1 because
9531 the if statement above ensured already that they are equal
9532 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533 for (i = 1; i < end_sub; ++i) {
9534 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9535 PyUnicode_READ(kind_sub, data_sub, i))
9536 return 0;
9537 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009538 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009539 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540 }
9541
9542 return 0;
9543}
9544
Alexander Belopolsky40018472011-02-26 01:02:56 +00009545Py_ssize_t
9546PyUnicode_Tailmatch(PyObject *str,
9547 PyObject *substr,
9548 Py_ssize_t start,
9549 Py_ssize_t end,
9550 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009552 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009553 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009554
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009555 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556}
9557
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009558static PyObject *
9559ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009561 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9562 char *resdata, *data = PyUnicode_DATA(self);
9563 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009564
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 res = PyUnicode_New(len, 127);
9566 if (res == NULL)
9567 return NULL;
9568 resdata = PyUnicode_DATA(res);
9569 if (lower)
9570 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009572 _Py_bytes_upper(resdata, data, len);
9573 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574}
9575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009576static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009577handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009579 Py_ssize_t j;
9580 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009581 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009582 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009583
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009584 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9585
9586 where ! is a negation and \p{xxx} is a character with property xxx.
9587 */
9588 for (j = i - 1; j >= 0; j--) {
9589 c = PyUnicode_READ(kind, data, j);
9590 if (!_PyUnicode_IsCaseIgnorable(c))
9591 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009592 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009593 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9594 if (final_sigma) {
9595 for (j = i + 1; j < length; j++) {
9596 c = PyUnicode_READ(kind, data, j);
9597 if (!_PyUnicode_IsCaseIgnorable(c))
9598 break;
9599 }
9600 final_sigma = j == length || !_PyUnicode_IsCased(c);
9601 }
9602 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009603}
9604
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009605static int
9606lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9607 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009608{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009609 /* Obscure special case. */
9610 if (c == 0x3A3) {
9611 mapped[0] = handle_capital_sigma(kind, data, length, i);
9612 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009614 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615}
9616
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009617static Py_ssize_t
9618do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009620 Py_ssize_t i, k = 0;
9621 int n_res, j;
9622 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009623
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624 c = PyUnicode_READ(kind, data, 0);
9625 n_res = _PyUnicode_ToUpperFull(c, mapped);
9626 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009627 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630 for (i = 1; i < length; i++) {
9631 c = PyUnicode_READ(kind, data, i);
9632 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9633 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009634 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009636 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009637 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639}
9640
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009641static Py_ssize_t
9642do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9643 Py_ssize_t i, k = 0;
9644
9645 for (i = 0; i < length; i++) {
9646 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9647 int n_res, j;
9648 if (Py_UNICODE_ISUPPER(c)) {
9649 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9650 }
9651 else if (Py_UNICODE_ISLOWER(c)) {
9652 n_res = _PyUnicode_ToUpperFull(c, mapped);
9653 }
9654 else {
9655 n_res = 1;
9656 mapped[0] = c;
9657 }
9658 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009659 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 res[k++] = mapped[j];
9661 }
9662 }
9663 return k;
9664}
9665
9666static Py_ssize_t
9667do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9668 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670 Py_ssize_t i, k = 0;
9671
9672 for (i = 0; i < length; i++) {
9673 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9674 int n_res, j;
9675 if (lower)
9676 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9677 else
9678 n_res = _PyUnicode_ToUpperFull(c, mapped);
9679 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009680 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 res[k++] = mapped[j];
9682 }
9683 }
9684 return k;
9685}
9686
9687static Py_ssize_t
9688do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9689{
9690 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9691}
9692
9693static Py_ssize_t
9694do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9695{
9696 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9697}
9698
Benjamin Petersone51757f2012-01-12 21:10:29 -05009699static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009700do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9701{
9702 Py_ssize_t i, k = 0;
9703
9704 for (i = 0; i < length; i++) {
9705 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9706 Py_UCS4 mapped[3];
9707 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9708 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009709 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009710 res[k++] = mapped[j];
9711 }
9712 }
9713 return k;
9714}
9715
9716static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009717do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9718{
9719 Py_ssize_t i, k = 0;
9720 int previous_is_cased;
9721
9722 previous_is_cased = 0;
9723 for (i = 0; i < length; i++) {
9724 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9725 Py_UCS4 mapped[3];
9726 int n_res, j;
9727
9728 if (previous_is_cased)
9729 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9730 else
9731 n_res = _PyUnicode_ToTitleFull(c, mapped);
9732
9733 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009734 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009735 res[k++] = mapped[j];
9736 }
9737
9738 previous_is_cased = _PyUnicode_IsCased(c);
9739 }
9740 return k;
9741}
9742
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009743static PyObject *
9744case_operation(PyObject *self,
9745 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9746{
9747 PyObject *res = NULL;
9748 Py_ssize_t length, newlength = 0;
9749 int kind, outkind;
9750 void *data, *outdata;
9751 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9752
Benjamin Petersoneea48462012-01-16 14:28:50 -05009753 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009754
9755 kind = PyUnicode_KIND(self);
9756 data = PyUnicode_DATA(self);
9757 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009758 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009759 PyErr_SetString(PyExc_OverflowError, "string is too long");
9760 return NULL;
9761 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009762 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009763 if (tmp == NULL)
9764 return PyErr_NoMemory();
9765 newlength = perform(kind, data, length, tmp, &maxchar);
9766 res = PyUnicode_New(newlength, maxchar);
9767 if (res == NULL)
9768 goto leave;
9769 tmpend = tmp + newlength;
9770 outdata = PyUnicode_DATA(res);
9771 outkind = PyUnicode_KIND(res);
9772 switch (outkind) {
9773 case PyUnicode_1BYTE_KIND:
9774 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9775 break;
9776 case PyUnicode_2BYTE_KIND:
9777 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9778 break;
9779 case PyUnicode_4BYTE_KIND:
9780 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9781 break;
9782 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009783 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009784 }
9785 leave:
9786 PyMem_FREE(tmp);
9787 return res;
9788}
9789
Tim Peters8ce9f162004-08-27 01:49:32 +00009790PyObject *
9791PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009792{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009793 PyObject *res;
9794 PyObject *fseq;
9795 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009796 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009798 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009799 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009800 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009801 }
9802
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009803 /* NOTE: the following code can't call back into Python code,
9804 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009805 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009806
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009807 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009808 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009809 res = _PyUnicode_JoinArray(separator, items, seqlen);
9810 Py_DECREF(fseq);
9811 return res;
9812}
9813
9814PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009815_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009816{
9817 PyObject *res = NULL; /* the result */
9818 PyObject *sep = NULL;
9819 Py_ssize_t seplen;
9820 PyObject *item;
9821 Py_ssize_t sz, i, res_offset;
9822 Py_UCS4 maxchar;
9823 Py_UCS4 item_maxchar;
9824 int use_memcpy;
9825 unsigned char *res_data = NULL, *sep_data = NULL;
9826 PyObject *last_obj;
9827 unsigned int kind = 0;
9828
Tim Peters05eba1f2004-08-27 21:32:02 +00009829 /* If empty sequence, return u"". */
9830 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009831 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009832 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009833
Tim Peters05eba1f2004-08-27 21:32:02 +00009834 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009835 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009836 if (seqlen == 1) {
9837 if (PyUnicode_CheckExact(items[0])) {
9838 res = items[0];
9839 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009840 return res;
9841 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009842 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009843 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009844 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009845 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009846 /* Set up sep and seplen */
9847 if (separator == NULL) {
9848 /* fall back to a blank space separator */
9849 sep = PyUnicode_FromOrdinal(' ');
9850 if (!sep)
9851 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009852 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009853 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009854 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009855 else {
9856 if (!PyUnicode_Check(separator)) {
9857 PyErr_Format(PyExc_TypeError,
9858 "separator: expected str instance,"
9859 " %.80s found",
9860 Py_TYPE(separator)->tp_name);
9861 goto onError;
9862 }
9863 if (PyUnicode_READY(separator))
9864 goto onError;
9865 sep = separator;
9866 seplen = PyUnicode_GET_LENGTH(separator);
9867 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9868 /* inc refcount to keep this code path symmetric with the
9869 above case of a blank separator */
9870 Py_INCREF(sep);
9871 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009872 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009873 }
9874
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009875 /* There are at least two things to join, or else we have a subclass
9876 * of str in the sequence.
9877 * Do a pre-pass to figure out the total amount of space we'll
9878 * need (sz), and see whether all argument are strings.
9879 */
9880 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009881#ifdef Py_DEBUG
9882 use_memcpy = 0;
9883#else
9884 use_memcpy = 1;
9885#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009886 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009887 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009888 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009889 if (!PyUnicode_Check(item)) {
9890 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009891 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009892 " %.80s found",
9893 i, Py_TYPE(item)->tp_name);
9894 goto onError;
9895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009896 if (PyUnicode_READY(item) == -1)
9897 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009898 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009900 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009901 if (i != 0) {
9902 add_sz += seplen;
9903 }
9904 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009905 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009906 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009907 goto onError;
9908 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009909 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009910 if (use_memcpy && last_obj != NULL) {
9911 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9912 use_memcpy = 0;
9913 }
9914 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009915 }
Tim Petersced69f82003-09-16 20:30:58 +00009916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009918 if (res == NULL)
9919 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009920
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009921 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009922#ifdef Py_DEBUG
9923 use_memcpy = 0;
9924#else
9925 if (use_memcpy) {
9926 res_data = PyUnicode_1BYTE_DATA(res);
9927 kind = PyUnicode_KIND(res);
9928 if (seplen != 0)
9929 sep_data = PyUnicode_1BYTE_DATA(sep);
9930 }
9931#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009932 if (use_memcpy) {
9933 for (i = 0; i < seqlen; ++i) {
9934 Py_ssize_t itemlen;
9935 item = items[i];
9936
9937 /* Copy item, and maybe the separator. */
9938 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009939 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009940 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009941 kind * seplen);
9942 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009943 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009944
9945 itemlen = PyUnicode_GET_LENGTH(item);
9946 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009947 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009948 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009949 kind * itemlen);
9950 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009951 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009952 }
9953 assert(res_data == PyUnicode_1BYTE_DATA(res)
9954 + kind * PyUnicode_GET_LENGTH(res));
9955 }
9956 else {
9957 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9958 Py_ssize_t itemlen;
9959 item = items[i];
9960
9961 /* Copy item, and maybe the separator. */
9962 if (i && seplen != 0) {
9963 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9964 res_offset += seplen;
9965 }
9966
9967 itemlen = PyUnicode_GET_LENGTH(item);
9968 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009969 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009970 res_offset += itemlen;
9971 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009972 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009973 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009974 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009977 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009979
Benjamin Peterson29060642009-01-31 22:14:21 +00009980 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009982 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009983 return NULL;
9984}
9985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009986#define FILL(kind, data, value, start, length) \
9987 do { \
9988 Py_ssize_t i_ = 0; \
9989 assert(kind != PyUnicode_WCHAR_KIND); \
9990 switch ((kind)) { \
9991 case PyUnicode_1BYTE_KIND: { \
9992 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009993 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009994 break; \
9995 } \
9996 case PyUnicode_2BYTE_KIND: { \
9997 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9998 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9999 break; \
10000 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010001 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10003 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10004 break; \
10005 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010006 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 } \
10008 } while (0)
10009
Victor Stinnerd3f08822012-05-29 12:57:52 +020010010void
10011_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10012 Py_UCS4 fill_char)
10013{
10014 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10015 const void *data = PyUnicode_DATA(unicode);
10016 assert(PyUnicode_IS_READY(unicode));
10017 assert(unicode_modifiable(unicode));
10018 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10019 assert(start >= 0);
10020 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10021 FILL(kind, data, fill_char, start, length);
10022}
10023
Victor Stinner3fe55312012-01-04 00:33:50 +010010024Py_ssize_t
10025PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10026 Py_UCS4 fill_char)
10027{
10028 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010029
10030 if (!PyUnicode_Check(unicode)) {
10031 PyErr_BadInternalCall();
10032 return -1;
10033 }
10034 if (PyUnicode_READY(unicode) == -1)
10035 return -1;
10036 if (unicode_check_modifiable(unicode))
10037 return -1;
10038
Victor Stinnerd3f08822012-05-29 12:57:52 +020010039 if (start < 0) {
10040 PyErr_SetString(PyExc_IndexError, "string index out of range");
10041 return -1;
10042 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010043 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10044 PyErr_SetString(PyExc_ValueError,
10045 "fill character is bigger than "
10046 "the string maximum character");
10047 return -1;
10048 }
10049
10050 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10051 length = Py_MIN(maxlen, length);
10052 if (length <= 0)
10053 return 0;
10054
Victor Stinnerd3f08822012-05-29 12:57:52 +020010055 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010056 return length;
10057}
10058
Victor Stinner9310abb2011-10-05 00:59:23 +020010059static PyObject *
10060pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010061 Py_ssize_t left,
10062 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010064{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 PyObject *u;
10066 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010067 int kind;
10068 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010069
10070 if (left < 0)
10071 left = 0;
10072 if (right < 0)
10073 right = 0;
10074
Victor Stinnerc4b49542011-12-11 22:44:26 +010010075 if (left == 0 && right == 0)
10076 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10079 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010080 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10081 return NULL;
10082 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010084 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010086 if (!u)
10087 return NULL;
10088
10089 kind = PyUnicode_KIND(u);
10090 data = PyUnicode_DATA(u);
10091 if (left)
10092 FILL(kind, data, fill, 0, left);
10093 if (right)
10094 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010095 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010096 assert(_PyUnicode_CheckConsistency(u, 1));
10097 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010098}
10099
Alexander Belopolsky40018472011-02-26 01:02:56 +000010100PyObject *
10101PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010102{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010104
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010105 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010106 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010107
Benjamin Petersonead6b532011-12-20 17:23:42 -060010108 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010110 if (PyUnicode_IS_ASCII(string))
10111 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010112 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010113 PyUnicode_GET_LENGTH(string), keepends);
10114 else
10115 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010116 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010117 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 break;
10119 case PyUnicode_2BYTE_KIND:
10120 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010121 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 PyUnicode_GET_LENGTH(string), keepends);
10123 break;
10124 case PyUnicode_4BYTE_KIND:
10125 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010126 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 PyUnicode_GET_LENGTH(string), keepends);
10128 break;
10129 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010130 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133}
10134
Alexander Belopolsky40018472011-02-26 01:02:56 +000010135static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010136split(PyObject *self,
10137 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010138 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010140 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 void *buf1, *buf2;
10142 Py_ssize_t len1, len2;
10143 PyObject* out;
10144
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010146 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 if (PyUnicode_READY(self) == -1)
10149 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010152 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010154 if (PyUnicode_IS_ASCII(self))
10155 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010156 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010157 PyUnicode_GET_LENGTH(self), maxcount
10158 );
10159 else
10160 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010161 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010162 PyUnicode_GET_LENGTH(self), maxcount
10163 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 case PyUnicode_2BYTE_KIND:
10165 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010166 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 PyUnicode_GET_LENGTH(self), maxcount
10168 );
10169 case PyUnicode_4BYTE_KIND:
10170 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010171 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 PyUnicode_GET_LENGTH(self), maxcount
10173 );
10174 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010175 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 }
10177
10178 if (PyUnicode_READY(substring) == -1)
10179 return NULL;
10180
10181 kind1 = PyUnicode_KIND(self);
10182 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 len1 = PyUnicode_GET_LENGTH(self);
10184 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010185 if (kind1 < kind2 || len1 < len2) {
10186 out = PyList_New(1);
10187 if (out == NULL)
10188 return NULL;
10189 Py_INCREF(self);
10190 PyList_SET_ITEM(out, 0, self);
10191 return out;
10192 }
10193 buf1 = PyUnicode_DATA(self);
10194 buf2 = PyUnicode_DATA(substring);
10195 if (kind2 != kind1) {
10196 buf2 = _PyUnicode_AsKind(substring, kind1);
10197 if (!buf2)
10198 return NULL;
10199 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010201 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010203 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10204 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010205 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206 else
10207 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010208 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 break;
10210 case PyUnicode_2BYTE_KIND:
10211 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010212 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 break;
10214 case PyUnicode_4BYTE_KIND:
10215 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010216 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 break;
10218 default:
10219 out = NULL;
10220 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010221 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 PyMem_Free(buf2);
10223 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010224}
10225
Alexander Belopolsky40018472011-02-26 01:02:56 +000010226static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010227rsplit(PyObject *self,
10228 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010229 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010230{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010231 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 void *buf1, *buf2;
10233 Py_ssize_t len1, len2;
10234 PyObject* out;
10235
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010236 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010237 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 if (PyUnicode_READY(self) == -1)
10240 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010243 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010245 if (PyUnicode_IS_ASCII(self))
10246 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010247 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010248 PyUnicode_GET_LENGTH(self), maxcount
10249 );
10250 else
10251 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010252 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010253 PyUnicode_GET_LENGTH(self), maxcount
10254 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 case PyUnicode_2BYTE_KIND:
10256 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010257 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 PyUnicode_GET_LENGTH(self), maxcount
10259 );
10260 case PyUnicode_4BYTE_KIND:
10261 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010262 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 PyUnicode_GET_LENGTH(self), maxcount
10264 );
10265 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010266 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 }
10268
10269 if (PyUnicode_READY(substring) == -1)
10270 return NULL;
10271
10272 kind1 = PyUnicode_KIND(self);
10273 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 len1 = PyUnicode_GET_LENGTH(self);
10275 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010276 if (kind1 < kind2 || len1 < len2) {
10277 out = PyList_New(1);
10278 if (out == NULL)
10279 return NULL;
10280 Py_INCREF(self);
10281 PyList_SET_ITEM(out, 0, self);
10282 return out;
10283 }
10284 buf1 = PyUnicode_DATA(self);
10285 buf2 = PyUnicode_DATA(substring);
10286 if (kind2 != kind1) {
10287 buf2 = _PyUnicode_AsKind(substring, kind1);
10288 if (!buf2)
10289 return NULL;
10290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010292 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010294 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10295 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010296 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010297 else
10298 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010299 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 break;
10301 case PyUnicode_2BYTE_KIND:
10302 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010303 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 break;
10305 case PyUnicode_4BYTE_KIND:
10306 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010307 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 break;
10309 default:
10310 out = NULL;
10311 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010312 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 PyMem_Free(buf2);
10314 return out;
10315}
10316
10317static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010318anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10319 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010321 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010323 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10324 return asciilib_find(buf1, len1, buf2, len2, offset);
10325 else
10326 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 case PyUnicode_2BYTE_KIND:
10328 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10329 case PyUnicode_4BYTE_KIND:
10330 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10331 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010332 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333}
10334
10335static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010336anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10337 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010339 switch (kind) {
10340 case PyUnicode_1BYTE_KIND:
10341 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10342 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10343 else
10344 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10345 case PyUnicode_2BYTE_KIND:
10346 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10347 case PyUnicode_4BYTE_KIND:
10348 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10349 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010350 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010351}
10352
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010353static void
10354replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10355 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10356{
10357 int kind = PyUnicode_KIND(u);
10358 void *data = PyUnicode_DATA(u);
10359 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10360 if (kind == PyUnicode_1BYTE_KIND) {
10361 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10362 (Py_UCS1 *)data + len,
10363 u1, u2, maxcount);
10364 }
10365 else if (kind == PyUnicode_2BYTE_KIND) {
10366 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10367 (Py_UCS2 *)data + len,
10368 u1, u2, maxcount);
10369 }
10370 else {
10371 assert(kind == PyUnicode_4BYTE_KIND);
10372 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10373 (Py_UCS4 *)data + len,
10374 u1, u2, maxcount);
10375 }
10376}
10377
Alexander Belopolsky40018472011-02-26 01:02:56 +000010378static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379replace(PyObject *self, PyObject *str1,
10380 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010381{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 PyObject *u;
10383 char *sbuf = PyUnicode_DATA(self);
10384 char *buf1 = PyUnicode_DATA(str1);
10385 char *buf2 = PyUnicode_DATA(str2);
10386 int srelease = 0, release1 = 0, release2 = 0;
10387 int skind = PyUnicode_KIND(self);
10388 int kind1 = PyUnicode_KIND(str1);
10389 int kind2 = PyUnicode_KIND(str2);
10390 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10391 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10392 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010393 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010394 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395
10396 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010397 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010399 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400
Victor Stinner59de0ee2011-10-07 10:01:28 +020010401 if (str1 == str2)
10402 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403
Victor Stinner49a0a212011-10-12 23:46:10 +020010404 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010405 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10406 if (maxchar < maxchar_str1)
10407 /* substring too wide to be present */
10408 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010409 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10410 /* Replacing str1 with str2 may cause a maxchar reduction in the
10411 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010412 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010413 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010418 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010420 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010421 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010422 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010423
Victor Stinner69ed0f42013-04-09 21:48:24 +020010424 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010425 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010426 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010428 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010430 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010432
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010433 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10434 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010435 }
10436 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 int rkind = skind;
10438 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010439 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 if (kind1 < rkind) {
10442 /* widen substring */
10443 buf1 = _PyUnicode_AsKind(str1, rkind);
10444 if (!buf1) goto error;
10445 release1 = 1;
10446 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010447 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010448 if (i < 0)
10449 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 if (rkind > kind2) {
10451 /* widen replacement */
10452 buf2 = _PyUnicode_AsKind(str2, rkind);
10453 if (!buf2) goto error;
10454 release2 = 1;
10455 }
10456 else if (rkind < kind2) {
10457 /* widen self and buf1 */
10458 rkind = kind2;
10459 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010460 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 sbuf = _PyUnicode_AsKind(self, rkind);
10462 if (!sbuf) goto error;
10463 srelease = 1;
10464 buf1 = _PyUnicode_AsKind(str1, rkind);
10465 if (!buf1) goto error;
10466 release1 = 1;
10467 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010468 u = PyUnicode_New(slen, maxchar);
10469 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010471 assert(PyUnicode_KIND(u) == rkind);
10472 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010473
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010474 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010475 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010476 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010478 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010480
10481 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010482 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010483 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010484 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010485 if (i == -1)
10486 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010487 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010489 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010493 }
10494 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010496 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 int rkind = skind;
10498 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010501 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 buf1 = _PyUnicode_AsKind(str1, rkind);
10503 if (!buf1) goto error;
10504 release1 = 1;
10505 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010506 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010507 if (n == 0)
10508 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010510 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 buf2 = _PyUnicode_AsKind(str2, rkind);
10512 if (!buf2) goto error;
10513 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010516 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 rkind = kind2;
10518 sbuf = _PyUnicode_AsKind(self, rkind);
10519 if (!sbuf) goto error;
10520 srelease = 1;
10521 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010522 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 buf1 = _PyUnicode_AsKind(str1, rkind);
10524 if (!buf1) goto error;
10525 release1 = 1;
10526 }
10527 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10528 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010529 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 PyErr_SetString(PyExc_OverflowError,
10531 "replace string is too long");
10532 goto error;
10533 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010534 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010535 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010536 _Py_INCREF_UNICODE_EMPTY();
10537 if (!unicode_empty)
10538 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 u = unicode_empty;
10540 goto done;
10541 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010542 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 PyErr_SetString(PyExc_OverflowError,
10544 "replace string is too long");
10545 goto error;
10546 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010547 u = PyUnicode_New(new_size, maxchar);
10548 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010550 assert(PyUnicode_KIND(u) == rkind);
10551 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 ires = i = 0;
10553 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 while (n-- > 0) {
10555 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010556 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010557 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010558 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010559 if (j == -1)
10560 break;
10561 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010562 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010563 memcpy(res + rkind * ires,
10564 sbuf + rkind * i,
10565 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010567 }
10568 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010570 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010572 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010574 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010578 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010579 memcpy(res + rkind * ires,
10580 sbuf + rkind * i,
10581 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010582 }
10583 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584 /* interleave */
10585 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010588 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010590 if (--n <= 0)
10591 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 memcpy(res + rkind * ires,
10593 sbuf + rkind * i,
10594 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 ires++;
10596 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010598 memcpy(res + rkind * ires,
10599 sbuf + rkind * i,
10600 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010601 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010602 }
10603
10604 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010605 unicode_adjust_maxchar(&u);
10606 if (u == NULL)
10607 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010608 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010609
10610 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 if (srelease)
10612 PyMem_FREE(sbuf);
10613 if (release1)
10614 PyMem_FREE(buf1);
10615 if (release2)
10616 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010617 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619
Benjamin Peterson29060642009-01-31 22:14:21 +000010620 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010621 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 if (srelease)
10623 PyMem_FREE(sbuf);
10624 if (release1)
10625 PyMem_FREE(buf1);
10626 if (release2)
10627 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010628 return unicode_result_unchanged(self);
10629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 error:
10631 if (srelease && sbuf)
10632 PyMem_FREE(sbuf);
10633 if (release1 && buf1)
10634 PyMem_FREE(buf1);
10635 if (release2 && buf2)
10636 PyMem_FREE(buf2);
10637 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638}
10639
10640/* --- Unicode Object Methods --------------------------------------------- */
10641
INADA Naoki3ae20562017-01-16 20:41:20 +090010642/*[clinic input]
10643str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644
INADA Naoki3ae20562017-01-16 20:41:20 +090010645Return a version of the string where each word is titlecased.
10646
10647More specifically, words start with uppercased characters and all remaining
10648cased characters have lower case.
10649[clinic start generated code]*/
10650
10651static PyObject *
10652unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010653/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010655 if (PyUnicode_READY(self) == -1)
10656 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010657 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658}
10659
INADA Naoki3ae20562017-01-16 20:41:20 +090010660/*[clinic input]
10661str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662
INADA Naoki3ae20562017-01-16 20:41:20 +090010663Return a capitalized version of the string.
10664
10665More specifically, make the first character have upper case and the rest lower
10666case.
10667[clinic start generated code]*/
10668
10669static PyObject *
10670unicode_capitalize_impl(PyObject *self)
10671/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010673 if (PyUnicode_READY(self) == -1)
10674 return NULL;
10675 if (PyUnicode_GET_LENGTH(self) == 0)
10676 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010677 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010678}
10679
INADA Naoki3ae20562017-01-16 20:41:20 +090010680/*[clinic input]
10681str.casefold as unicode_casefold
10682
10683Return a version of the string suitable for caseless comparisons.
10684[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010685
10686static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010687unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010688/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010689{
10690 if (PyUnicode_READY(self) == -1)
10691 return NULL;
10692 if (PyUnicode_IS_ASCII(self))
10693 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010694 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010695}
10696
10697
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010698/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010699
10700static int
10701convert_uc(PyObject *obj, void *addr)
10702{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010704
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010705 if (!PyUnicode_Check(obj)) {
10706 PyErr_Format(PyExc_TypeError,
10707 "The fill character must be a unicode character, "
10708 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010709 return 0;
10710 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010711 if (PyUnicode_READY(obj) < 0)
10712 return 0;
10713 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010714 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010715 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010716 return 0;
10717 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010718 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010719 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010720}
10721
INADA Naoki3ae20562017-01-16 20:41:20 +090010722/*[clinic input]
10723str.center as unicode_center
10724
10725 width: Py_ssize_t
10726 fillchar: Py_UCS4 = ' '
10727 /
10728
10729Return a centered string of length width.
10730
10731Padding is done using the specified fill character (default is a space).
10732[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010733
10734static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010735unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10736/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010737{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010738 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739
Benjamin Petersonbac79492012-01-14 13:34:47 -050010740 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741 return NULL;
10742
Victor Stinnerc4b49542011-12-11 22:44:26 +010010743 if (PyUnicode_GET_LENGTH(self) >= width)
10744 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745
Victor Stinnerc4b49542011-12-11 22:44:26 +010010746 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747 left = marg / 2 + (marg & width & 1);
10748
Victor Stinner9310abb2011-10-05 00:59:23 +020010749 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750}
10751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752/* This function assumes that str1 and str2 are readied by the caller. */
10753
Marc-André Lemburge5034372000-08-08 08:04:29 +000010754static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010755unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010756{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010757#define COMPARE(TYPE1, TYPE2) \
10758 do { \
10759 TYPE1* p1 = (TYPE1 *)data1; \
10760 TYPE2* p2 = (TYPE2 *)data2; \
10761 TYPE1* end = p1 + len; \
10762 Py_UCS4 c1, c2; \
10763 for (; p1 != end; p1++, p2++) { \
10764 c1 = *p1; \
10765 c2 = *p2; \
10766 if (c1 != c2) \
10767 return (c1 < c2) ? -1 : 1; \
10768 } \
10769 } \
10770 while (0)
10771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 int kind1, kind2;
10773 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010774 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010775
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010776 kind1 = PyUnicode_KIND(str1);
10777 kind2 = PyUnicode_KIND(str2);
10778 data1 = PyUnicode_DATA(str1);
10779 data2 = PyUnicode_DATA(str2);
10780 len1 = PyUnicode_GET_LENGTH(str1);
10781 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010782 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010783
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010784 switch(kind1) {
10785 case PyUnicode_1BYTE_KIND:
10786 {
10787 switch(kind2) {
10788 case PyUnicode_1BYTE_KIND:
10789 {
10790 int cmp = memcmp(data1, data2, len);
10791 /* normalize result of memcmp() into the range [-1; 1] */
10792 if (cmp < 0)
10793 return -1;
10794 if (cmp > 0)
10795 return 1;
10796 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010797 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010798 case PyUnicode_2BYTE_KIND:
10799 COMPARE(Py_UCS1, Py_UCS2);
10800 break;
10801 case PyUnicode_4BYTE_KIND:
10802 COMPARE(Py_UCS1, Py_UCS4);
10803 break;
10804 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010805 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010806 }
10807 break;
10808 }
10809 case PyUnicode_2BYTE_KIND:
10810 {
10811 switch(kind2) {
10812 case PyUnicode_1BYTE_KIND:
10813 COMPARE(Py_UCS2, Py_UCS1);
10814 break;
10815 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010816 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010817 COMPARE(Py_UCS2, Py_UCS2);
10818 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010819 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010820 case PyUnicode_4BYTE_KIND:
10821 COMPARE(Py_UCS2, Py_UCS4);
10822 break;
10823 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010824 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010825 }
10826 break;
10827 }
10828 case PyUnicode_4BYTE_KIND:
10829 {
10830 switch(kind2) {
10831 case PyUnicode_1BYTE_KIND:
10832 COMPARE(Py_UCS4, Py_UCS1);
10833 break;
10834 case PyUnicode_2BYTE_KIND:
10835 COMPARE(Py_UCS4, Py_UCS2);
10836 break;
10837 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010838 {
10839#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10840 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10841 /* normalize result of wmemcmp() into the range [-1; 1] */
10842 if (cmp < 0)
10843 return -1;
10844 if (cmp > 0)
10845 return 1;
10846#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010847 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010848#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010849 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010850 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010851 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010852 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010853 }
10854 break;
10855 }
10856 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010857 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010858 }
10859
Victor Stinner770e19e2012-10-04 22:59:45 +020010860 if (len1 == len2)
10861 return 0;
10862 if (len1 < len2)
10863 return -1;
10864 else
10865 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010866
10867#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010868}
10869
Benjamin Peterson621b4302016-09-09 13:54:34 -070010870static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010871unicode_compare_eq(PyObject *str1, PyObject *str2)
10872{
10873 int kind;
10874 void *data1, *data2;
10875 Py_ssize_t len;
10876 int cmp;
10877
Victor Stinnere5567ad2012-10-23 02:48:49 +020010878 len = PyUnicode_GET_LENGTH(str1);
10879 if (PyUnicode_GET_LENGTH(str2) != len)
10880 return 0;
10881 kind = PyUnicode_KIND(str1);
10882 if (PyUnicode_KIND(str2) != kind)
10883 return 0;
10884 data1 = PyUnicode_DATA(str1);
10885 data2 = PyUnicode_DATA(str2);
10886
10887 cmp = memcmp(data1, data2, len * kind);
10888 return (cmp == 0);
10889}
10890
10891
Alexander Belopolsky40018472011-02-26 01:02:56 +000010892int
10893PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10896 if (PyUnicode_READY(left) == -1 ||
10897 PyUnicode_READY(right) == -1)
10898 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010899
10900 /* a string is equal to itself */
10901 if (left == right)
10902 return 0;
10903
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010904 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010905 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010906 PyErr_Format(PyExc_TypeError,
10907 "Can't compare %.100s and %.100s",
10908 left->ob_type->tp_name,
10909 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910 return -1;
10911}
10912
Martin v. Löwis5b222132007-06-10 09:51:05 +000010913int
10914PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10915{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010916 Py_ssize_t i;
10917 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010919 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010920
Victor Stinner910337b2011-10-03 03:20:16 +020010921 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010922 if (!PyUnicode_IS_READY(uni)) {
10923 const wchar_t *ws = _PyUnicode_WSTR(uni);
10924 /* Compare Unicode string and source character set string */
10925 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10926 if (chr != ustr[i])
10927 return (chr < ustr[i]) ? -1 : 1;
10928 }
10929 /* This check keeps Python strings that end in '\0' from comparing equal
10930 to C strings identical up to that point. */
10931 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10932 return 1; /* uni is longer */
10933 if (ustr[i])
10934 return -1; /* str is longer */
10935 return 0;
10936 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010938 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010939 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010940 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010941 size_t len, len2 = strlen(str);
10942 int cmp;
10943
10944 len = Py_MIN(len1, len2);
10945 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010946 if (cmp != 0) {
10947 if (cmp < 0)
10948 return -1;
10949 else
10950 return 1;
10951 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010952 if (len1 > len2)
10953 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010954 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010955 return -1; /* str is longer */
10956 return 0;
10957 }
10958 else {
10959 void *data = PyUnicode_DATA(uni);
10960 /* Compare Unicode string and source character set string */
10961 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010962 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010963 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10964 /* This check keeps Python strings that end in '\0' from comparing equal
10965 to C strings identical up to that point. */
10966 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10967 return 1; /* uni is longer */
10968 if (str[i])
10969 return -1; /* str is longer */
10970 return 0;
10971 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010972}
10973
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010974static int
10975non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10976{
10977 size_t i, len;
10978 const wchar_t *p;
10979 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10980 if (strlen(str) != len)
10981 return 0;
10982 p = _PyUnicode_WSTR(unicode);
10983 assert(p);
10984 for (i = 0; i < len; i++) {
10985 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020010986 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010987 return 0;
10988 }
10989 return 1;
10990}
10991
10992int
10993_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
10994{
10995 size_t len;
10996 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020010997 assert(str);
10998#ifndef NDEBUG
10999 for (const char *p = str; *p; p++) {
11000 assert((unsigned char)*p < 128);
11001 }
11002#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011003 if (PyUnicode_READY(unicode) == -1) {
11004 /* Memory error or bad data */
11005 PyErr_Clear();
11006 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11007 }
11008 if (!PyUnicode_IS_ASCII(unicode))
11009 return 0;
11010 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11011 return strlen(str) == len &&
11012 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11013}
11014
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011015int
11016_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11017{
11018 PyObject *right_uni;
11019 Py_hash_t hash;
11020
11021 assert(_PyUnicode_CHECK(left));
11022 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011023#ifndef NDEBUG
11024 for (const char *p = right->string; *p; p++) {
11025 assert((unsigned char)*p < 128);
11026 }
11027#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011028
11029 if (PyUnicode_READY(left) == -1) {
11030 /* memory error or bad data */
11031 PyErr_Clear();
11032 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11033 }
11034
11035 if (!PyUnicode_IS_ASCII(left))
11036 return 0;
11037
11038 right_uni = _PyUnicode_FromId(right); /* borrowed */
11039 if (right_uni == NULL) {
11040 /* memory error or bad data */
11041 PyErr_Clear();
11042 return _PyUnicode_EqualToASCIIString(left, right->string);
11043 }
11044
11045 if (left == right_uni)
11046 return 1;
11047
11048 if (PyUnicode_CHECK_INTERNED(left))
11049 return 0;
11050
INADA Naoki7cc95f52018-01-28 02:07:09 +090011051 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011052 hash = _PyUnicode_HASH(left);
11053 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11054 return 0;
11055
11056 return unicode_compare_eq(left, right_uni);
11057}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011058
Alexander Belopolsky40018472011-02-26 01:02:56 +000011059PyObject *
11060PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011061{
11062 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011063
Victor Stinnere5567ad2012-10-23 02:48:49 +020011064 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11065 Py_RETURN_NOTIMPLEMENTED;
11066
11067 if (PyUnicode_READY(left) == -1 ||
11068 PyUnicode_READY(right) == -1)
11069 return NULL;
11070
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011071 if (left == right) {
11072 switch (op) {
11073 case Py_EQ:
11074 case Py_LE:
11075 case Py_GE:
11076 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011077 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011078 case Py_NE:
11079 case Py_LT:
11080 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011081 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011082 default:
11083 PyErr_BadArgument();
11084 return NULL;
11085 }
11086 }
11087 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011088 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011089 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011090 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011091 }
11092 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011093 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011094 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011095 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011096}
11097
Alexander Belopolsky40018472011-02-26 01:02:56 +000011098int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011099_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11100{
11101 return unicode_eq(aa, bb);
11102}
11103
11104int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011105PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011106{
Victor Stinner77282cb2013-04-14 19:22:47 +020011107 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011108 void *buf1, *buf2;
11109 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011110 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011111
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011112 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011113 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011114 "'in <string>' requires string as left operand, not %.100s",
11115 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011116 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011117 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011118 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011119 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011120 if (ensure_unicode(str) < 0)
11121 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011124 kind2 = PyUnicode_KIND(substr);
11125 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011126 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011128 len2 = PyUnicode_GET_LENGTH(substr);
11129 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011130 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011131 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011132 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011133 if (len2 == 1) {
11134 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11135 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 return result;
11137 }
11138 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011139 buf2 = _PyUnicode_AsKind(substr, kind1);
11140 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011141 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143
Victor Stinner77282cb2013-04-14 19:22:47 +020011144 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 case PyUnicode_1BYTE_KIND:
11146 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11147 break;
11148 case PyUnicode_2BYTE_KIND:
11149 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11150 break;
11151 case PyUnicode_4BYTE_KIND:
11152 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11153 break;
11154 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011155 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011157
Victor Stinner77282cb2013-04-14 19:22:47 +020011158 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 PyMem_Free(buf2);
11160
Guido van Rossum403d68b2000-03-13 15:55:09 +000011161 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011162}
11163
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164/* Concat to string or Unicode object giving a new Unicode object. */
11165
Alexander Belopolsky40018472011-02-26 01:02:56 +000011166PyObject *
11167PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011169 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011170 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011171 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011173 if (ensure_unicode(left) < 0)
11174 return NULL;
11175
11176 if (!PyUnicode_Check(right)) {
11177 PyErr_Format(PyExc_TypeError,
11178 "can only concatenate str (not \"%.200s\") to str",
11179 right->ob_type->tp_name);
11180 return NULL;
11181 }
11182 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011183 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011184
11185 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011186 if (left == unicode_empty)
11187 return PyUnicode_FromObject(right);
11188 if (right == unicode_empty)
11189 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011191 left_len = PyUnicode_GET_LENGTH(left);
11192 right_len = PyUnicode_GET_LENGTH(right);
11193 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011194 PyErr_SetString(PyExc_OverflowError,
11195 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011196 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011197 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011199
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011200 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11201 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011202 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011205 result = PyUnicode_New(new_len, maxchar);
11206 if (result == NULL)
11207 return NULL;
11208 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11209 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11210 assert(_PyUnicode_CheckConsistency(result, 1));
11211 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212}
11213
Walter Dörwald1ab83302007-05-18 17:15:44 +000011214void
Victor Stinner23e56682011-10-03 03:54:37 +020011215PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011216{
Victor Stinner23e56682011-10-03 03:54:37 +020011217 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011218 Py_UCS4 maxchar, maxchar2;
11219 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011220
11221 if (p_left == NULL) {
11222 if (!PyErr_Occurred())
11223 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011224 return;
11225 }
Victor Stinner23e56682011-10-03 03:54:37 +020011226 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011227 if (right == NULL || left == NULL
11228 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011229 if (!PyErr_Occurred())
11230 PyErr_BadInternalCall();
11231 goto error;
11232 }
11233
Benjamin Petersonbac79492012-01-14 13:34:47 -050011234 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011235 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011236 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011237 goto error;
11238
Victor Stinner488fa492011-12-12 00:01:39 +010011239 /* Shortcuts */
11240 if (left == unicode_empty) {
11241 Py_DECREF(left);
11242 Py_INCREF(right);
11243 *p_left = right;
11244 return;
11245 }
11246 if (right == unicode_empty)
11247 return;
11248
11249 left_len = PyUnicode_GET_LENGTH(left);
11250 right_len = PyUnicode_GET_LENGTH(right);
11251 if (left_len > PY_SSIZE_T_MAX - right_len) {
11252 PyErr_SetString(PyExc_OverflowError,
11253 "strings are too large to concat");
11254 goto error;
11255 }
11256 new_len = left_len + right_len;
11257
11258 if (unicode_modifiable(left)
11259 && PyUnicode_CheckExact(right)
11260 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011261 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11262 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011263 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011264 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011265 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11266 {
11267 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011268 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011269 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011270
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011271 /* copy 'right' into the newly allocated area of 'left' */
11272 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011273 }
Victor Stinner488fa492011-12-12 00:01:39 +010011274 else {
11275 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11276 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011277 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011278
Victor Stinner488fa492011-12-12 00:01:39 +010011279 /* Concat the two Unicode strings */
11280 res = PyUnicode_New(new_len, maxchar);
11281 if (res == NULL)
11282 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011283 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11284 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011285 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011286 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011287 }
11288 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011289 return;
11290
11291error:
Victor Stinner488fa492011-12-12 00:01:39 +010011292 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011293}
11294
11295void
11296PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11297{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011298 PyUnicode_Append(pleft, right);
11299 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011300}
11301
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011302/*
11303Wraps stringlib_parse_args_finds() and additionally ensures that the
11304first argument is a unicode object.
11305*/
11306
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011307static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011308parse_args_finds_unicode(const char * function_name, PyObject *args,
11309 PyObject **substring,
11310 Py_ssize_t *start, Py_ssize_t *end)
11311{
11312 if(stringlib_parse_args_finds(function_name, args, substring,
11313 start, end)) {
11314 if (ensure_unicode(*substring) < 0)
11315 return 0;
11316 return 1;
11317 }
11318 return 0;
11319}
11320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011321PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011322 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011324Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011325string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011326interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327
11328static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011329unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011331 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011332 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011333 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011335 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 void *buf1, *buf2;
11337 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011339 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011340 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011342 kind1 = PyUnicode_KIND(self);
11343 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011344 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011345 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 len1 = PyUnicode_GET_LENGTH(self);
11348 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011350 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011351 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011352
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011353 buf1 = PyUnicode_DATA(self);
11354 buf2 = PyUnicode_DATA(substring);
11355 if (kind2 != kind1) {
11356 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011357 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011358 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011359 }
11360 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 case PyUnicode_1BYTE_KIND:
11362 iresult = ucs1lib_count(
11363 ((Py_UCS1*)buf1) + start, end - start,
11364 buf2, len2, PY_SSIZE_T_MAX
11365 );
11366 break;
11367 case PyUnicode_2BYTE_KIND:
11368 iresult = ucs2lib_count(
11369 ((Py_UCS2*)buf1) + start, end - start,
11370 buf2, len2, PY_SSIZE_T_MAX
11371 );
11372 break;
11373 case PyUnicode_4BYTE_KIND:
11374 iresult = ucs4lib_count(
11375 ((Py_UCS4*)buf1) + start, end - start,
11376 buf2, len2, PY_SSIZE_T_MAX
11377 );
11378 break;
11379 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011380 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 }
11382
11383 result = PyLong_FromSsize_t(iresult);
11384
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011385 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388 return result;
11389}
11390
INADA Naoki3ae20562017-01-16 20:41:20 +090011391/*[clinic input]
11392str.encode as unicode_encode
11393
11394 encoding: str(c_default="NULL") = 'utf-8'
11395 The encoding in which to encode the string.
11396 errors: str(c_default="NULL") = 'strict'
11397 The error handling scheme to use for encoding errors.
11398 The default is 'strict' meaning that encoding errors raise a
11399 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11400 'xmlcharrefreplace' as well as any other name registered with
11401 codecs.register_error that can handle UnicodeEncodeErrors.
11402
11403Encode the string using the codec registered for encoding.
11404[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405
11406static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011407unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011408/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011410 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011411}
11412
INADA Naoki3ae20562017-01-16 20:41:20 +090011413/*[clinic input]
11414str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415
INADA Naoki3ae20562017-01-16 20:41:20 +090011416 tabsize: int = 8
11417
11418Return a copy where all tab characters are expanded using spaces.
11419
11420If tabsize is not given, a tab size of 8 characters is assumed.
11421[clinic start generated code]*/
11422
11423static PyObject *
11424unicode_expandtabs_impl(PyObject *self, int tabsize)
11425/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011427 Py_ssize_t i, j, line_pos, src_len, incr;
11428 Py_UCS4 ch;
11429 PyObject *u;
11430 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011431 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011432 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433
Antoine Pitrou22425222011-10-04 19:10:51 +020011434 if (PyUnicode_READY(self) == -1)
11435 return NULL;
11436
Thomas Wouters7e474022000-07-16 12:04:32 +000011437 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 src_len = PyUnicode_GET_LENGTH(self);
11439 i = j = line_pos = 0;
11440 kind = PyUnicode_KIND(self);
11441 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011442 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011443 for (; i < src_len; i++) {
11444 ch = PyUnicode_READ(kind, src_data, i);
11445 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011446 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011448 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 goto overflow;
11451 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011453 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011457 goto overflow;
11458 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011460 if (ch == '\n' || ch == '\r')
11461 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011464 if (!found)
11465 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011466
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011468 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 if (!u)
11470 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011471 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472
Antoine Pitroue71d5742011-10-04 15:55:09 +020011473 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474
Antoine Pitroue71d5742011-10-04 15:55:09 +020011475 for (; i < src_len; i++) {
11476 ch = PyUnicode_READ(kind, src_data, i);
11477 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 incr = tabsize - (line_pos % tabsize);
11480 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011481 FILL(kind, dest_data, ' ', j, incr);
11482 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011484 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 line_pos++;
11487 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011488 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011489 if (ch == '\n' || ch == '\r')
11490 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011492 }
11493 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011494 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011495
Antoine Pitroue71d5742011-10-04 15:55:09 +020011496 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011497 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499}
11500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011501PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011502 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503\n\
11504Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011505such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506arguments start and end are interpreted as in slice notation.\n\
11507\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011508Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
11510static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011513 /* initialize variables to prevent gcc warning */
11514 PyObject *substring = NULL;
11515 Py_ssize_t start = 0;
11516 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011517 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011519 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011522 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011525 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (result == -2)
11528 return NULL;
11529
Christian Heimes217cfd12007-12-02 14:31:20 +000011530 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531}
11532
11533static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011534unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011536 void *data;
11537 enum PyUnicode_Kind kind;
11538 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011539
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011540 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011541 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011543 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011544 if (PyUnicode_READY(self) == -1) {
11545 return NULL;
11546 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011547 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11548 PyErr_SetString(PyExc_IndexError, "string index out of range");
11549 return NULL;
11550 }
11551 kind = PyUnicode_KIND(self);
11552 data = PyUnicode_DATA(self);
11553 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011554 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555}
11556
Guido van Rossumc2504932007-09-18 19:42:40 +000011557/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011558 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011559static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011560unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561{
Guido van Rossumc2504932007-09-18 19:42:40 +000011562 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011563 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011564
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011565#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011566 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011567#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 if (_PyUnicode_HASH(self) != -1)
11569 return _PyUnicode_HASH(self);
11570 if (PyUnicode_READY(self) == -1)
11571 return -1;
11572 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011573 /*
11574 We make the hash of the empty string be 0, rather than using
11575 (prefix ^ suffix), since this slightly obfuscates the hash secret
11576 */
11577 if (len == 0) {
11578 _PyUnicode_HASH(self) = 0;
11579 return 0;
11580 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011581 x = _Py_HashBytes(PyUnicode_DATA(self),
11582 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011583 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011584 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585}
11586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589\n\
oldkaa0735f2018-02-02 16:52:55 +080011590Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011591such that sub is contained within S[start:end]. Optional\n\
11592arguments start and end are interpreted as in slice notation.\n\
11593\n\
11594Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
11596static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011599 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011600 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011601 PyObject *substring = NULL;
11602 Py_ssize_t start = 0;
11603 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011605 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011608 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011609 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011610
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011611 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 if (result == -2)
11614 return NULL;
11615
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616 if (result < 0) {
11617 PyErr_SetString(PyExc_ValueError, "substring not found");
11618 return NULL;
11619 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011620
Christian Heimes217cfd12007-12-02 14:31:20 +000011621 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622}
11623
INADA Naoki3ae20562017-01-16 20:41:20 +090011624/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011625str.isascii as unicode_isascii
11626
11627Return True if all characters in the string are ASCII, False otherwise.
11628
11629ASCII characters have code points in the range U+0000-U+007F.
11630Empty string is ASCII too.
11631[clinic start generated code]*/
11632
11633static PyObject *
11634unicode_isascii_impl(PyObject *self)
11635/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11636{
11637 if (PyUnicode_READY(self) == -1) {
11638 return NULL;
11639 }
11640 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11641}
11642
11643/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011644str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645
INADA Naoki3ae20562017-01-16 20:41:20 +090011646Return True if the string is a lowercase string, False otherwise.
11647
11648A string is lowercase if all cased characters in the string are lowercase and
11649there is at least one cased character in the string.
11650[clinic start generated code]*/
11651
11652static PyObject *
11653unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011654/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 Py_ssize_t i, length;
11657 int kind;
11658 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659 int cased;
11660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 if (PyUnicode_READY(self) == -1)
11662 return NULL;
11663 length = PyUnicode_GET_LENGTH(self);
11664 kind = PyUnicode_KIND(self);
11665 data = PyUnicode_DATA(self);
11666
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 if (length == 1)
11669 return PyBool_FromLong(
11670 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011672 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011674 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011675
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 for (i = 0; i < length; i++) {
11678 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011679
Benjamin Peterson29060642009-01-31 22:14:21 +000011680 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011681 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 else if (!cased && Py_UNICODE_ISLOWER(ch))
11683 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011685 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686}
11687
INADA Naoki3ae20562017-01-16 20:41:20 +090011688/*[clinic input]
11689str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
INADA Naoki3ae20562017-01-16 20:41:20 +090011691Return True if the string is an uppercase string, False otherwise.
11692
11693A string is uppercase if all cased characters in the string are uppercase and
11694there is at least one cased character in the string.
11695[clinic start generated code]*/
11696
11697static PyObject *
11698unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011699/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 Py_ssize_t i, length;
11702 int kind;
11703 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704 int cased;
11705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 if (PyUnicode_READY(self) == -1)
11707 return NULL;
11708 length = PyUnicode_GET_LENGTH(self);
11709 kind = PyUnicode_KIND(self);
11710 data = PyUnicode_DATA(self);
11711
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 if (length == 1)
11714 return PyBool_FromLong(
11715 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011717 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011719 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011720
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 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_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011726 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 else if (!cased && Py_UNICODE_ISUPPER(ch))
11728 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011730 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731}
11732
INADA Naoki3ae20562017-01-16 20:41:20 +090011733/*[clinic input]
11734str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735
INADA Naoki3ae20562017-01-16 20:41:20 +090011736Return True if the string is a title-cased string, False otherwise.
11737
11738In a title-cased string, upper- and title-case characters may only
11739follow uncased characters and lowercase characters only cased ones.
11740[clinic start generated code]*/
11741
11742static PyObject *
11743unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011744/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 Py_ssize_t i, length;
11747 int kind;
11748 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749 int cased, previous_is_cased;
11750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 if (PyUnicode_READY(self) == -1)
11752 return NULL;
11753 length = PyUnicode_GET_LENGTH(self);
11754 kind = PyUnicode_KIND(self);
11755 data = PyUnicode_DATA(self);
11756
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 if (length == 1) {
11759 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11760 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11761 (Py_UNICODE_ISUPPER(ch) != 0));
11762 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011764 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011766 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011767
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768 cased = 0;
11769 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 for (i = 0; i < length; i++) {
11771 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011772
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11774 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011775 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011776 previous_is_cased = 1;
11777 cased = 1;
11778 }
11779 else if (Py_UNICODE_ISLOWER(ch)) {
11780 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011781 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 previous_is_cased = 1;
11783 cased = 1;
11784 }
11785 else
11786 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011788 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789}
11790
INADA Naoki3ae20562017-01-16 20:41:20 +090011791/*[clinic input]
11792str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793
INADA Naoki3ae20562017-01-16 20:41:20 +090011794Return True if the string is a whitespace string, False otherwise.
11795
11796A string is whitespace if all characters in the string are whitespace and there
11797is at least one character in the string.
11798[clinic start generated code]*/
11799
11800static PyObject *
11801unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011802/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 Py_ssize_t i, length;
11805 int kind;
11806 void *data;
11807
11808 if (PyUnicode_READY(self) == -1)
11809 return NULL;
11810 length = PyUnicode_GET_LENGTH(self);
11811 kind = PyUnicode_KIND(self);
11812 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 if (length == 1)
11816 return PyBool_FromLong(
11817 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011818
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011819 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011821 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 for (i = 0; i < length; i++) {
11824 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011825 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011826 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011828 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829}
11830
INADA Naoki3ae20562017-01-16 20:41:20 +090011831/*[clinic input]
11832str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011833
INADA Naoki3ae20562017-01-16 20:41:20 +090011834Return True if the string is an alphabetic string, False otherwise.
11835
11836A string is alphabetic if all characters in the string are alphabetic and there
11837is at least one character in the string.
11838[clinic start generated code]*/
11839
11840static PyObject *
11841unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011842/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011843{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011844 Py_ssize_t i, length;
11845 int kind;
11846 void *data;
11847
11848 if (PyUnicode_READY(self) == -1)
11849 return NULL;
11850 length = PyUnicode_GET_LENGTH(self);
11851 kind = PyUnicode_KIND(self);
11852 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011853
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011854 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011855 if (length == 1)
11856 return PyBool_FromLong(
11857 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011858
11859 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011860 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011861 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 for (i = 0; i < length; i++) {
11864 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011865 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011866 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011867 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011868}
11869
INADA Naoki3ae20562017-01-16 20:41:20 +090011870/*[clinic input]
11871str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872
INADA Naoki3ae20562017-01-16 20:41:20 +090011873Return True if the string is an alpha-numeric string, False otherwise.
11874
11875A string is alpha-numeric if all characters in the string are alpha-numeric and
11876there is at least one character in the string.
11877[clinic start generated code]*/
11878
11879static PyObject *
11880unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011881/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011882{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 int kind;
11884 void *data;
11885 Py_ssize_t len, i;
11886
11887 if (PyUnicode_READY(self) == -1)
11888 return NULL;
11889
11890 kind = PyUnicode_KIND(self);
11891 data = PyUnicode_DATA(self);
11892 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011893
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011894 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 if (len == 1) {
11896 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11897 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11898 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011899
11900 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011902 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 for (i = 0; i < len; i++) {
11905 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011906 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011907 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011908 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011909 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011910}
11911
INADA Naoki3ae20562017-01-16 20:41:20 +090011912/*[clinic input]
11913str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914
INADA Naoki3ae20562017-01-16 20:41:20 +090011915Return True if the string is a decimal string, False otherwise.
11916
11917A string is a decimal string if all characters in the string are decimal and
11918there is at least one character in the string.
11919[clinic start generated code]*/
11920
11921static PyObject *
11922unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011923/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 Py_ssize_t i, length;
11926 int kind;
11927 void *data;
11928
11929 if (PyUnicode_READY(self) == -1)
11930 return NULL;
11931 length = PyUnicode_GET_LENGTH(self);
11932 kind = PyUnicode_KIND(self);
11933 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 if (length == 1)
11937 return PyBool_FromLong(
11938 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011940 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011942 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 for (i = 0; i < length; i++) {
11945 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011946 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011948 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949}
11950
INADA Naoki3ae20562017-01-16 20:41:20 +090011951/*[clinic input]
11952str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953
INADA Naoki3ae20562017-01-16 20:41:20 +090011954Return True if the string is a digit string, False otherwise.
11955
11956A string is a digit string if all characters in the string are digits and there
11957is at least one character in the string.
11958[clinic start generated code]*/
11959
11960static PyObject *
11961unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011962/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 Py_ssize_t i, length;
11965 int kind;
11966 void *data;
11967
11968 if (PyUnicode_READY(self) == -1)
11969 return NULL;
11970 length = PyUnicode_GET_LENGTH(self);
11971 kind = PyUnicode_KIND(self);
11972 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011973
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 if (length == 1) {
11976 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11977 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11978 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011980 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011982 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011984 for (i = 0; i < length; i++) {
11985 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011986 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011987 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011988 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989}
11990
INADA Naoki3ae20562017-01-16 20:41:20 +090011991/*[clinic input]
11992str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993
INADA Naoki3ae20562017-01-16 20:41:20 +090011994Return True if the string is a numeric string, False otherwise.
11995
11996A string is numeric if all characters in the string are numeric and there is at
11997least one character in the string.
11998[clinic start generated code]*/
11999
12000static PyObject *
12001unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012002/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 Py_ssize_t i, length;
12005 int kind;
12006 void *data;
12007
12008 if (PyUnicode_READY(self) == -1)
12009 return NULL;
12010 length = PyUnicode_GET_LENGTH(self);
12011 kind = PyUnicode_KIND(self);
12012 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013
Guido van Rossumd57fd912000-03-10 22:53:23 +000012014 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 if (length == 1)
12016 return PyBool_FromLong(
12017 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012019 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012021 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 for (i = 0; i < length; i++) {
12024 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012025 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012026 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012027 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012028}
12029
Martin v. Löwis47383402007-08-15 07:32:56 +000012030int
12031PyUnicode_IsIdentifier(PyObject *self)
12032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 int kind;
12034 void *data;
12035 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012036 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 if (PyUnicode_READY(self) == -1) {
12039 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 }
12042
12043 /* Special case for empty strings */
12044 if (PyUnicode_GET_LENGTH(self) == 0)
12045 return 0;
12046 kind = PyUnicode_KIND(self);
12047 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012048
12049 /* PEP 3131 says that the first character must be in
12050 XID_Start and subsequent characters in XID_Continue,
12051 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012052 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012053 letters, digits, underscore). However, given the current
12054 definition of XID_Start and XID_Continue, it is sufficient
12055 to check just for these, except that _ must be allowed
12056 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012058 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012059 return 0;
12060
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012061 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012063 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012064 return 1;
12065}
12066
INADA Naoki3ae20562017-01-16 20:41:20 +090012067/*[clinic input]
12068str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012069
INADA Naoki3ae20562017-01-16 20:41:20 +090012070Return True if the string is a valid Python identifier, False otherwise.
12071
12072Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12073"class".
12074[clinic start generated code]*/
12075
12076static PyObject *
12077unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012078/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012079{
12080 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12081}
12082
INADA Naoki3ae20562017-01-16 20:41:20 +090012083/*[clinic input]
12084str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012085
INADA Naoki3ae20562017-01-16 20:41:20 +090012086Return True if the string is printable, False otherwise.
12087
12088A string is printable if all of its characters are considered printable in
12089repr() or if it is empty.
12090[clinic start generated code]*/
12091
12092static PyObject *
12093unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012094/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 Py_ssize_t i, length;
12097 int kind;
12098 void *data;
12099
12100 if (PyUnicode_READY(self) == -1)
12101 return NULL;
12102 length = PyUnicode_GET_LENGTH(self);
12103 kind = PyUnicode_KIND(self);
12104 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012105
12106 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 if (length == 1)
12108 return PyBool_FromLong(
12109 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 for (i = 0; i < length; i++) {
12112 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012113 Py_RETURN_FALSE;
12114 }
12115 }
12116 Py_RETURN_TRUE;
12117}
12118
INADA Naoki3ae20562017-01-16 20:41:20 +090012119/*[clinic input]
12120str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121
INADA Naoki3ae20562017-01-16 20:41:20 +090012122 iterable: object
12123 /
12124
12125Concatenate any number of strings.
12126
Martin Panter91a88662017-01-24 00:30:06 +000012127The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012128The result is returned as a new string.
12129
12130Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12131[clinic start generated code]*/
12132
12133static PyObject *
12134unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012135/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136{
INADA Naoki3ae20562017-01-16 20:41:20 +090012137 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138}
12139
Martin v. Löwis18e16552006-02-15 17:27:45 +000012140static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012141unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 if (PyUnicode_READY(self) == -1)
12144 return -1;
12145 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146}
12147
INADA Naoki3ae20562017-01-16 20:41:20 +090012148/*[clinic input]
12149str.ljust as unicode_ljust
12150
12151 width: Py_ssize_t
12152 fillchar: Py_UCS4 = ' '
12153 /
12154
12155Return a left-justified string of length width.
12156
12157Padding is done using the specified fill character (default is a space).
12158[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159
12160static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012161unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12162/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012164 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012165 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166
Victor Stinnerc4b49542011-12-11 22:44:26 +010012167 if (PyUnicode_GET_LENGTH(self) >= width)
12168 return unicode_result_unchanged(self);
12169
12170 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171}
12172
INADA Naoki3ae20562017-01-16 20:41:20 +090012173/*[clinic input]
12174str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
INADA Naoki3ae20562017-01-16 20:41:20 +090012176Return a copy of the string converted to lowercase.
12177[clinic start generated code]*/
12178
12179static PyObject *
12180unicode_lower_impl(PyObject *self)
12181/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012183 if (PyUnicode_READY(self) == -1)
12184 return NULL;
12185 if (PyUnicode_IS_ASCII(self))
12186 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012187 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188}
12189
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012190#define LEFTSTRIP 0
12191#define RIGHTSTRIP 1
12192#define BOTHSTRIP 2
12193
12194/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012195static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012196
INADA Naoki3ae20562017-01-16 20:41:20 +090012197#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012198
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012199/* externally visible for str.strip(unicode) */
12200PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012201_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 void *data;
12204 int kind;
12205 Py_ssize_t i, j, len;
12206 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012207 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12210 return NULL;
12211
12212 kind = PyUnicode_KIND(self);
12213 data = PyUnicode_DATA(self);
12214 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012215 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012216 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12217 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012218 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012219
Benjamin Peterson14339b62009-01-31 16:36:08 +000012220 i = 0;
12221 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012222 while (i < len) {
12223 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12224 if (!BLOOM(sepmask, ch))
12225 break;
12226 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12227 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012228 i++;
12229 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012230 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012231
Benjamin Peterson14339b62009-01-31 16:36:08 +000012232 j = len;
12233 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012234 j--;
12235 while (j >= i) {
12236 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12237 if (!BLOOM(sepmask, ch))
12238 break;
12239 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12240 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012241 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012242 }
12243
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012245 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012246
Victor Stinner7931d9a2011-11-04 00:22:48 +010012247 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248}
12249
12250PyObject*
12251PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12252{
12253 unsigned char *data;
12254 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012255 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256
Victor Stinnerde636f32011-10-01 03:55:54 +020012257 if (PyUnicode_READY(self) == -1)
12258 return NULL;
12259
Victor Stinner684d5fd2012-05-03 02:32:34 +020012260 length = PyUnicode_GET_LENGTH(self);
12261 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012262
Victor Stinner684d5fd2012-05-03 02:32:34 +020012263 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012264 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265
Victor Stinnerde636f32011-10-01 03:55:54 +020012266 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012267 PyErr_SetString(PyExc_IndexError, "string index out of range");
12268 return NULL;
12269 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012270 if (start >= length || end < start)
12271 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012272
Victor Stinner684d5fd2012-05-03 02:32:34 +020012273 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012274 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012275 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012276 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012277 }
12278 else {
12279 kind = PyUnicode_KIND(self);
12280 data = PyUnicode_1BYTE_DATA(self);
12281 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012282 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012283 length);
12284 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286
12287static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012288do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012290 Py_ssize_t len, i, j;
12291
12292 if (PyUnicode_READY(self) == -1)
12293 return NULL;
12294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012296
Victor Stinnercc7af722013-04-09 22:39:24 +020012297 if (PyUnicode_IS_ASCII(self)) {
12298 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12299
12300 i = 0;
12301 if (striptype != RIGHTSTRIP) {
12302 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012303 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012304 if (!_Py_ascii_whitespace[ch])
12305 break;
12306 i++;
12307 }
12308 }
12309
12310 j = len;
12311 if (striptype != LEFTSTRIP) {
12312 j--;
12313 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012314 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012315 if (!_Py_ascii_whitespace[ch])
12316 break;
12317 j--;
12318 }
12319 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012320 }
12321 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012322 else {
12323 int kind = PyUnicode_KIND(self);
12324 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012325
Victor Stinnercc7af722013-04-09 22:39:24 +020012326 i = 0;
12327 if (striptype != RIGHTSTRIP) {
12328 while (i < len) {
12329 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12330 if (!Py_UNICODE_ISSPACE(ch))
12331 break;
12332 i++;
12333 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012334 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012335
12336 j = len;
12337 if (striptype != LEFTSTRIP) {
12338 j--;
12339 while (j >= i) {
12340 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12341 if (!Py_UNICODE_ISSPACE(ch))
12342 break;
12343 j--;
12344 }
12345 j++;
12346 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012347 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012348
Victor Stinner7931d9a2011-11-04 00:22:48 +010012349 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350}
12351
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012352
12353static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012354do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012355{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012356 if (sep != NULL && sep != Py_None) {
12357 if (PyUnicode_Check(sep))
12358 return _PyUnicode_XStrip(self, striptype, sep);
12359 else {
12360 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012361 "%s arg must be None or str",
12362 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012363 return NULL;
12364 }
12365 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012366
Benjamin Peterson14339b62009-01-31 16:36:08 +000012367 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012368}
12369
12370
INADA Naoki3ae20562017-01-16 20:41:20 +090012371/*[clinic input]
12372str.strip as unicode_strip
12373
12374 chars: object = None
12375 /
12376
Victor Stinner0c4a8282017-01-17 02:21:47 +010012377Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012378
12379If chars is given and not None, remove characters in chars instead.
12380[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012381
12382static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012383unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012384/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012385{
INADA Naoki3ae20562017-01-16 20:41:20 +090012386 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012387}
12388
12389
INADA Naoki3ae20562017-01-16 20:41:20 +090012390/*[clinic input]
12391str.lstrip as unicode_lstrip
12392
12393 chars: object = NULL
12394 /
12395
12396Return a copy of the string with leading whitespace removed.
12397
12398If chars is given and not None, remove characters in chars instead.
12399[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012400
12401static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012402unicode_lstrip_impl(PyObject *self, PyObject *chars)
12403/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012404{
INADA Naoki3ae20562017-01-16 20:41:20 +090012405 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012406}
12407
12408
INADA Naoki3ae20562017-01-16 20:41:20 +090012409/*[clinic input]
12410str.rstrip as unicode_rstrip
12411
12412 chars: object = NULL
12413 /
12414
12415Return a copy of the string with trailing whitespace removed.
12416
12417If chars is given and not None, remove characters in chars instead.
12418[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012419
12420static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012421unicode_rstrip_impl(PyObject *self, PyObject *chars)
12422/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012423{
INADA Naoki3ae20562017-01-16 20:41:20 +090012424 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012425}
12426
12427
Guido van Rossumd57fd912000-03-10 22:53:23 +000012428static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012429unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012430{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012431 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433
Serhiy Storchaka05997252013-01-26 12:14:02 +020012434 if (len < 1)
12435 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012436
Victor Stinnerc4b49542011-12-11 22:44:26 +010012437 /* no repeat, return original string */
12438 if (len == 1)
12439 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012440
Benjamin Petersonbac79492012-01-14 13:34:47 -050012441 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 return NULL;
12443
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012444 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012445 PyErr_SetString(PyExc_OverflowError,
12446 "repeated string is too long");
12447 return NULL;
12448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012450
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012451 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452 if (!u)
12453 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012454 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 if (PyUnicode_GET_LENGTH(str) == 1) {
12457 const int kind = PyUnicode_KIND(str);
12458 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012459 if (kind == PyUnicode_1BYTE_KIND) {
12460 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012461 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012462 }
12463 else if (kind == PyUnicode_2BYTE_KIND) {
12464 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012465 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012466 ucs2[n] = fill_char;
12467 } else {
12468 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12469 assert(kind == PyUnicode_4BYTE_KIND);
12470 for (n = 0; n < len; ++n)
12471 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012472 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 }
12474 else {
12475 /* number of characters copied this far */
12476 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012477 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012479 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012481 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012483 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012484 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012485 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486 }
12487
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012488 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012489 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490}
12491
Alexander Belopolsky40018472011-02-26 01:02:56 +000012492PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012493PyUnicode_Replace(PyObject *str,
12494 PyObject *substr,
12495 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012496 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012497{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012498 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12499 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012500 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012501 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012502}
12503
INADA Naoki3ae20562017-01-16 20:41:20 +090012504/*[clinic input]
12505str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506
INADA Naoki3ae20562017-01-16 20:41:20 +090012507 old: unicode
12508 new: unicode
12509 count: Py_ssize_t = -1
12510 Maximum number of occurrences to replace.
12511 -1 (the default value) means replace all occurrences.
12512 /
12513
12514Return a copy with all occurrences of substring old replaced by new.
12515
12516If the optional argument count is given, only the first count occurrences are
12517replaced.
12518[clinic start generated code]*/
12519
12520static PyObject *
12521unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12522 Py_ssize_t count)
12523/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012525 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012526 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012527 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528}
12529
Alexander Belopolsky40018472011-02-26 01:02:56 +000012530static PyObject *
12531unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012533 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 Py_ssize_t isize;
12535 Py_ssize_t osize, squote, dquote, i, o;
12536 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012537 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012541 return NULL;
12542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 isize = PyUnicode_GET_LENGTH(unicode);
12544 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 /* Compute length of output, quote characters, and
12547 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012548 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 max = 127;
12550 squote = dquote = 0;
12551 ikind = PyUnicode_KIND(unicode);
12552 for (i = 0; i < isize; i++) {
12553 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012554 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012556 case '\'': squote++; break;
12557 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012559 incr = 2;
12560 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 default:
12562 /* Fast-path ASCII */
12563 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012564 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012566 ;
12567 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012570 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012572 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012574 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 if (osize > PY_SSIZE_T_MAX - incr) {
12577 PyErr_SetString(PyExc_OverflowError,
12578 "string is too long to generate repr");
12579 return NULL;
12580 }
12581 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 }
12583
12584 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012585 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012587 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 if (dquote)
12589 /* Both squote and dquote present. Use squote,
12590 and escape them */
12591 osize += squote;
12592 else
12593 quote = '"';
12594 }
Victor Stinner55c08782013-04-14 18:45:39 +020012595 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012596
12597 repr = PyUnicode_New(osize, max);
12598 if (repr == NULL)
12599 return NULL;
12600 okind = PyUnicode_KIND(repr);
12601 odata = PyUnicode_DATA(repr);
12602
12603 PyUnicode_WRITE(okind, odata, 0, quote);
12604 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012605 if (unchanged) {
12606 _PyUnicode_FastCopyCharacters(repr, 1,
12607 unicode, 0,
12608 isize);
12609 }
12610 else {
12611 for (i = 0, o = 1; i < isize; i++) {
12612 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613
Victor Stinner55c08782013-04-14 18:45:39 +020012614 /* Escape quotes and backslashes */
12615 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012616 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012618 continue;
12619 }
12620
12621 /* Map special whitespace to '\t', \n', '\r' */
12622 if (ch == '\t') {
12623 PyUnicode_WRITE(okind, odata, o++, '\\');
12624 PyUnicode_WRITE(okind, odata, o++, 't');
12625 }
12626 else if (ch == '\n') {
12627 PyUnicode_WRITE(okind, odata, o++, '\\');
12628 PyUnicode_WRITE(okind, odata, o++, 'n');
12629 }
12630 else if (ch == '\r') {
12631 PyUnicode_WRITE(okind, odata, o++, '\\');
12632 PyUnicode_WRITE(okind, odata, o++, 'r');
12633 }
12634
12635 /* Map non-printable US ASCII to '\xhh' */
12636 else if (ch < ' ' || ch == 0x7F) {
12637 PyUnicode_WRITE(okind, odata, o++, '\\');
12638 PyUnicode_WRITE(okind, odata, o++, 'x');
12639 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12640 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12641 }
12642
12643 /* Copy ASCII characters as-is */
12644 else if (ch < 0x7F) {
12645 PyUnicode_WRITE(okind, odata, o++, ch);
12646 }
12647
12648 /* Non-ASCII characters */
12649 else {
12650 /* Map Unicode whitespace and control characters
12651 (categories Z* and C* except ASCII space)
12652 */
12653 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12654 PyUnicode_WRITE(okind, odata, o++, '\\');
12655 /* Map 8-bit characters to '\xhh' */
12656 if (ch <= 0xff) {
12657 PyUnicode_WRITE(okind, odata, o++, 'x');
12658 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12659 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12660 }
12661 /* Map 16-bit characters to '\uxxxx' */
12662 else if (ch <= 0xffff) {
12663 PyUnicode_WRITE(okind, odata, o++, 'u');
12664 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12665 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12666 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12667 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12668 }
12669 /* Map 21-bit characters to '\U00xxxxxx' */
12670 else {
12671 PyUnicode_WRITE(okind, odata, o++, 'U');
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12674 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12675 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12677 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12680 }
12681 }
12682 /* Copy characters as-is */
12683 else {
12684 PyUnicode_WRITE(okind, odata, o++, ch);
12685 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012686 }
12687 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012688 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012690 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012691 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692}
12693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012694PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696\n\
12697Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012698such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699arguments start and end are interpreted as in slice notation.\n\
12700\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012701Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702
12703static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012706 /* initialize variables to prevent gcc warning */
12707 PyObject *substring = NULL;
12708 Py_ssize_t start = 0;
12709 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012710 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012712 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012713 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012715 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012718 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012720 if (result == -2)
12721 return NULL;
12722
Christian Heimes217cfd12007-12-02 14:31:20 +000012723 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724}
12725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012726PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012727 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012729Return the highest index in S where substring sub is found,\n\
12730such that sub is contained within S[start:end]. Optional\n\
12731arguments start and end are interpreted as in slice notation.\n\
12732\n\
12733Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734
12735static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012738 /* initialize variables to prevent gcc warning */
12739 PyObject *substring = NULL;
12740 Py_ssize_t start = 0;
12741 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012742 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012744 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012745 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012746
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012747 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012749
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012750 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012752 if (result == -2)
12753 return NULL;
12754
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755 if (result < 0) {
12756 PyErr_SetString(PyExc_ValueError, "substring not found");
12757 return NULL;
12758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759
Christian Heimes217cfd12007-12-02 14:31:20 +000012760 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761}
12762
INADA Naoki3ae20562017-01-16 20:41:20 +090012763/*[clinic input]
12764str.rjust as unicode_rjust
12765
12766 width: Py_ssize_t
12767 fillchar: Py_UCS4 = ' '
12768 /
12769
12770Return a right-justified string of length width.
12771
12772Padding is done using the specified fill character (default is a space).
12773[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774
12775static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012776unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12777/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012779 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780 return NULL;
12781
Victor Stinnerc4b49542011-12-11 22:44:26 +010012782 if (PyUnicode_GET_LENGTH(self) >= width)
12783 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784
Victor Stinnerc4b49542011-12-11 22:44:26 +010012785 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786}
12787
Alexander Belopolsky40018472011-02-26 01:02:56 +000012788PyObject *
12789PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012791 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012792 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012794 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795}
12796
INADA Naoki3ae20562017-01-16 20:41:20 +090012797/*[clinic input]
12798str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
INADA Naoki3ae20562017-01-16 20:41:20 +090012800 sep: object = None
12801 The delimiter according which to split the string.
12802 None (the default value) means split according to any whitespace,
12803 and discard empty strings from the result.
12804 maxsplit: Py_ssize_t = -1
12805 Maximum number of splits to do.
12806 -1 (the default value) means no limit.
12807
12808Return a list of the words in the string, using sep as the delimiter string.
12809[clinic start generated code]*/
12810
12811static PyObject *
12812unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12813/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814{
INADA Naoki3ae20562017-01-16 20:41:20 +090012815 if (sep == Py_None)
12816 return split(self, NULL, maxsplit);
12817 if (PyUnicode_Check(sep))
12818 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012819
12820 PyErr_Format(PyExc_TypeError,
12821 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012822 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012823 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824}
12825
Thomas Wouters477c8d52006-05-27 19:21:47 +000012826PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012827PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012828{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012829 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012830 int kind1, kind2;
12831 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012832 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012833
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012834 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836
Victor Stinner14f8f022011-10-05 20:58:25 +020012837 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 len1 = PyUnicode_GET_LENGTH(str_obj);
12840 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012841 if (kind1 < kind2 || len1 < len2) {
12842 _Py_INCREF_UNICODE_EMPTY();
12843 if (!unicode_empty)
12844 out = NULL;
12845 else {
12846 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12847 Py_DECREF(unicode_empty);
12848 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012849 return out;
12850 }
12851 buf1 = PyUnicode_DATA(str_obj);
12852 buf2 = PyUnicode_DATA(sep_obj);
12853 if (kind2 != kind1) {
12854 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12855 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012856 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012859 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012860 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012861 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12862 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12863 else
12864 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012865 break;
12866 case PyUnicode_2BYTE_KIND:
12867 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12868 break;
12869 case PyUnicode_4BYTE_KIND:
12870 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12871 break;
12872 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012873 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012875
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012876 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878
12879 return out;
12880}
12881
12882
12883PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012884PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012885{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012886 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012887 int kind1, kind2;
12888 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012889 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012890
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012891 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012892 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012893
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012894 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012896 len1 = PyUnicode_GET_LENGTH(str_obj);
12897 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012898 if (kind1 < kind2 || len1 < len2) {
12899 _Py_INCREF_UNICODE_EMPTY();
12900 if (!unicode_empty)
12901 out = NULL;
12902 else {
12903 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12904 Py_DECREF(unicode_empty);
12905 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012906 return out;
12907 }
12908 buf1 = PyUnicode_DATA(str_obj);
12909 buf2 = PyUnicode_DATA(sep_obj);
12910 if (kind2 != kind1) {
12911 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12912 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012913 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012914 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012915
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012916 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012918 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12919 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12920 else
12921 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012922 break;
12923 case PyUnicode_2BYTE_KIND:
12924 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12925 break;
12926 case PyUnicode_4BYTE_KIND:
12927 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12928 break;
12929 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012930 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012931 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012932
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012933 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012934 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012935
12936 return out;
12937}
12938
INADA Naoki3ae20562017-01-16 20:41:20 +090012939/*[clinic input]
12940str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012941
INADA Naoki3ae20562017-01-16 20:41:20 +090012942 sep: object
12943 /
12944
12945Partition the string into three parts using the given separator.
12946
12947This will search for the separator in the string. If the separator is found,
12948returns a 3-tuple containing the part before the separator, the separator
12949itself, and the part after it.
12950
12951If the separator is not found, returns a 3-tuple containing the original string
12952and two empty strings.
12953[clinic start generated code]*/
12954
12955static PyObject *
12956unicode_partition(PyObject *self, PyObject *sep)
12957/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012958{
INADA Naoki3ae20562017-01-16 20:41:20 +090012959 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012960}
12961
INADA Naoki3ae20562017-01-16 20:41:20 +090012962/*[clinic input]
12963str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012964
INADA Naoki3ae20562017-01-16 20:41:20 +090012965Partition the string into three parts using the given separator.
12966
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012967This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012968the separator is found, returns a 3-tuple containing the part before the
12969separator, the separator itself, and the part after it.
12970
12971If the separator is not found, returns a 3-tuple containing two empty strings
12972and the original string.
12973[clinic start generated code]*/
12974
12975static PyObject *
12976unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012977/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978{
INADA Naoki3ae20562017-01-16 20:41:20 +090012979 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012980}
12981
Alexander Belopolsky40018472011-02-26 01:02:56 +000012982PyObject *
12983PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012984{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012985 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012986 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012987
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012988 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012989}
12990
INADA Naoki3ae20562017-01-16 20:41:20 +090012991/*[clinic input]
12992str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012993
INADA Naoki3ae20562017-01-16 20:41:20 +090012994Return a list of the words in the string, using sep as the delimiter string.
12995
12996Splits are done starting at the end of the string and working to the front.
12997[clinic start generated code]*/
12998
12999static PyObject *
13000unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13001/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013002{
INADA Naoki3ae20562017-01-16 20:41:20 +090013003 if (sep == Py_None)
13004 return rsplit(self, NULL, maxsplit);
13005 if (PyUnicode_Check(sep))
13006 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013007
13008 PyErr_Format(PyExc_TypeError,
13009 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013010 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013011 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013012}
13013
INADA Naoki3ae20562017-01-16 20:41:20 +090013014/*[clinic input]
13015str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013016
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013017 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013018
13019Return a list of the lines in the string, breaking at line boundaries.
13020
13021Line breaks are not included in the resulting list unless keepends is given and
13022true.
13023[clinic start generated code]*/
13024
13025static PyObject *
13026unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013027/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013028{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013029 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013030}
13031
13032static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013033PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013035 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013036}
13037
INADA Naoki3ae20562017-01-16 20:41:20 +090013038/*[clinic input]
13039str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040
INADA Naoki3ae20562017-01-16 20:41:20 +090013041Convert uppercase characters to lowercase and lowercase characters to uppercase.
13042[clinic start generated code]*/
13043
13044static PyObject *
13045unicode_swapcase_impl(PyObject *self)
13046/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013048 if (PyUnicode_READY(self) == -1)
13049 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013050 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051}
13052
Larry Hastings61272b72014-01-07 12:41:53 -080013053/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013054
Larry Hastings31826802013-10-19 00:09:25 -070013055@staticmethod
13056str.maketrans as unicode_maketrans
13057
13058 x: object
13059
13060 y: unicode=NULL
13061
13062 z: unicode=NULL
13063
13064 /
13065
13066Return a translation table usable for str.translate().
13067
13068If there is only one argument, it must be a dictionary mapping Unicode
13069ordinals (integers) or characters to Unicode ordinals, strings or None.
13070Character keys will be then converted to ordinals.
13071If there are two arguments, they must be strings of equal length, and
13072in the resulting dictionary, each character in x will be mapped to the
13073character at the same position in y. If there is a third argument, it
13074must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013075[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013076
Larry Hastings31826802013-10-19 00:09:25 -070013077static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013078unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013079/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013080{
Georg Brandlceee0772007-11-27 23:48:05 +000013081 PyObject *new = NULL, *key, *value;
13082 Py_ssize_t i = 0;
13083 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013084
Georg Brandlceee0772007-11-27 23:48:05 +000013085 new = PyDict_New();
13086 if (!new)
13087 return NULL;
13088 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013089 int x_kind, y_kind, z_kind;
13090 void *x_data, *y_data, *z_data;
13091
Georg Brandlceee0772007-11-27 23:48:05 +000013092 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013093 if (!PyUnicode_Check(x)) {
13094 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13095 "be a string if there is a second argument");
13096 goto err;
13097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013098 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013099 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13100 "arguments must have equal length");
13101 goto err;
13102 }
13103 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 x_kind = PyUnicode_KIND(x);
13105 y_kind = PyUnicode_KIND(y);
13106 x_data = PyUnicode_DATA(x);
13107 y_data = PyUnicode_DATA(y);
13108 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13109 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013110 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013111 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013112 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013113 if (!value) {
13114 Py_DECREF(key);
13115 goto err;
13116 }
Georg Brandlceee0772007-11-27 23:48:05 +000013117 res = PyDict_SetItem(new, key, value);
13118 Py_DECREF(key);
13119 Py_DECREF(value);
13120 if (res < 0)
13121 goto err;
13122 }
13123 /* create entries for deleting chars in z */
13124 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013125 z_kind = PyUnicode_KIND(z);
13126 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013127 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013129 if (!key)
13130 goto err;
13131 res = PyDict_SetItem(new, key, Py_None);
13132 Py_DECREF(key);
13133 if (res < 0)
13134 goto err;
13135 }
13136 }
13137 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013138 int kind;
13139 void *data;
13140
Georg Brandlceee0772007-11-27 23:48:05 +000013141 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013142 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013143 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13144 "to maketrans it must be a dict");
13145 goto err;
13146 }
13147 /* copy entries into the new dict, converting string keys to int keys */
13148 while (PyDict_Next(x, &i, &key, &value)) {
13149 if (PyUnicode_Check(key)) {
13150 /* convert string keys to integer keys */
13151 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013152 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013153 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13154 "table must be of length 1");
13155 goto err;
13156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 kind = PyUnicode_KIND(key);
13158 data = PyUnicode_DATA(key);
13159 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013160 if (!newkey)
13161 goto err;
13162 res = PyDict_SetItem(new, newkey, value);
13163 Py_DECREF(newkey);
13164 if (res < 0)
13165 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013166 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013167 /* just keep integer keys */
13168 if (PyDict_SetItem(new, key, value) < 0)
13169 goto err;
13170 } else {
13171 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13172 "be strings or integers");
13173 goto err;
13174 }
13175 }
13176 }
13177 return new;
13178 err:
13179 Py_DECREF(new);
13180 return NULL;
13181}
13182
INADA Naoki3ae20562017-01-16 20:41:20 +090013183/*[clinic input]
13184str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013185
INADA Naoki3ae20562017-01-16 20:41:20 +090013186 table: object
13187 Translation table, which must be a mapping of Unicode ordinals to
13188 Unicode ordinals, strings, or None.
13189 /
13190
13191Replace each character in the string using the given translation table.
13192
13193The table must implement lookup/indexing via __getitem__, for instance a
13194dictionary or list. If this operation raises LookupError, the character is
13195left untouched. Characters mapped to None are deleted.
13196[clinic start generated code]*/
13197
13198static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013199unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013200/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013202 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203}
13204
INADA Naoki3ae20562017-01-16 20:41:20 +090013205/*[clinic input]
13206str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207
INADA Naoki3ae20562017-01-16 20:41:20 +090013208Return a copy of the string converted to uppercase.
13209[clinic start generated code]*/
13210
13211static PyObject *
13212unicode_upper_impl(PyObject *self)
13213/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013215 if (PyUnicode_READY(self) == -1)
13216 return NULL;
13217 if (PyUnicode_IS_ASCII(self))
13218 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013219 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220}
13221
INADA Naoki3ae20562017-01-16 20:41:20 +090013222/*[clinic input]
13223str.zfill as unicode_zfill
13224
13225 width: Py_ssize_t
13226 /
13227
13228Pad a numeric string with zeros on the left, to fill a field of the given width.
13229
13230The string is never truncated.
13231[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232
13233static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013234unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013235/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013237 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013238 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013239 int kind;
13240 void *data;
13241 Py_UCS4 chr;
13242
Benjamin Petersonbac79492012-01-14 13:34:47 -050013243 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013244 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245
Victor Stinnerc4b49542011-12-11 22:44:26 +010013246 if (PyUnicode_GET_LENGTH(self) >= width)
13247 return unicode_result_unchanged(self);
13248
13249 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250
13251 u = pad(self, fill, 0, '0');
13252
Walter Dörwald068325e2002-04-15 13:36:47 +000013253 if (u == NULL)
13254 return NULL;
13255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013256 kind = PyUnicode_KIND(u);
13257 data = PyUnicode_DATA(u);
13258 chr = PyUnicode_READ(kind, data, fill);
13259
13260 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 PyUnicode_WRITE(kind, data, 0, chr);
13263 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013264 }
13265
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013266 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013267 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269
13270#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013271static PyObject *
13272unicode__decimal2ascii(PyObject *self)
13273{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013274 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013275}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013276#endif
13277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013278PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013281Return True if S starts with the specified prefix, False otherwise.\n\
13282With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013283With optional end, stop comparing S at that position.\n\
13284prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013285
13286static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013287unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013289{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013290 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013291 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013292 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013293 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013294 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295
Jesus Ceaac451502011-04-20 17:09:23 +020013296 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013297 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013298 if (PyTuple_Check(subobj)) {
13299 Py_ssize_t i;
13300 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013301 substring = PyTuple_GET_ITEM(subobj, i);
13302 if (!PyUnicode_Check(substring)) {
13303 PyErr_Format(PyExc_TypeError,
13304 "tuple for startswith must only contain str, "
13305 "not %.100s",
13306 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013307 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013308 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013309 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013310 if (result == -1)
13311 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013312 if (result) {
13313 Py_RETURN_TRUE;
13314 }
13315 }
13316 /* nothing matched */
13317 Py_RETURN_FALSE;
13318 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013319 if (!PyUnicode_Check(subobj)) {
13320 PyErr_Format(PyExc_TypeError,
13321 "startswith first arg must be str or "
13322 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013323 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013324 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013325 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013326 if (result == -1)
13327 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013328 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013329}
13330
13331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013332PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013333 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013334\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013335Return True if S ends with the specified suffix, False otherwise.\n\
13336With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013337With optional end, stop comparing S at that position.\n\
13338suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339
13340static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013341unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013342 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013344 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013345 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013346 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013347 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013348 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349
Jesus Ceaac451502011-04-20 17:09:23 +020013350 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013351 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013352 if (PyTuple_Check(subobj)) {
13353 Py_ssize_t i;
13354 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013355 substring = PyTuple_GET_ITEM(subobj, i);
13356 if (!PyUnicode_Check(substring)) {
13357 PyErr_Format(PyExc_TypeError,
13358 "tuple for endswith must only contain str, "
13359 "not %.100s",
13360 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013361 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013362 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013363 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013364 if (result == -1)
13365 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013366 if (result) {
13367 Py_RETURN_TRUE;
13368 }
13369 }
13370 Py_RETURN_FALSE;
13371 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013372 if (!PyUnicode_Check(subobj)) {
13373 PyErr_Format(PyExc_TypeError,
13374 "endswith first arg must be str or "
13375 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013377 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013378 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013379 if (result == -1)
13380 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013381 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013382}
13383
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013384static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013385_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013386{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013387 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13388 writer->data = PyUnicode_DATA(writer->buffer);
13389
13390 if (!writer->readonly) {
13391 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013392 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013393 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013394 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013395 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13396 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13397 writer->kind = PyUnicode_WCHAR_KIND;
13398 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13399
Victor Stinner8f674cc2013-04-17 23:02:17 +020013400 /* Copy-on-write mode: set buffer size to 0 so
13401 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13402 * next write. */
13403 writer->size = 0;
13404 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013405}
13406
Victor Stinnerd3f08822012-05-29 12:57:52 +020013407void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013408_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013409{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013410 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013411
13412 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013413 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013414
13415 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13416 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13417 writer->kind = PyUnicode_WCHAR_KIND;
13418 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013419}
13420
Victor Stinnerd3f08822012-05-29 12:57:52 +020013421int
13422_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13423 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013424{
13425 Py_ssize_t newlen;
13426 PyObject *newbuffer;
13427
Victor Stinner2740e462016-09-06 16:58:36 -070013428 assert(maxchar <= MAX_UNICODE);
13429
Victor Stinnerca9381e2015-09-22 00:58:32 +020013430 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013431 assert((maxchar > writer->maxchar && length >= 0)
13432 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013433
Victor Stinner202fdca2012-05-07 12:47:02 +020013434 if (length > PY_SSIZE_T_MAX - writer->pos) {
13435 PyErr_NoMemory();
13436 return -1;
13437 }
13438 newlen = writer->pos + length;
13439
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013440 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013441
Victor Stinnerd3f08822012-05-29 12:57:52 +020013442 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013443 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013444 if (writer->overallocate
13445 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13446 /* overallocate to limit the number of realloc() */
13447 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013448 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013449 if (newlen < writer->min_length)
13450 newlen = writer->min_length;
13451
Victor Stinnerd3f08822012-05-29 12:57:52 +020013452 writer->buffer = PyUnicode_New(newlen, maxchar);
13453 if (writer->buffer == NULL)
13454 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013455 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013456 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013457 if (writer->overallocate
13458 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13459 /* overallocate to limit the number of realloc() */
13460 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013461 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013462 if (newlen < writer->min_length)
13463 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013464
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013465 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013466 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013467 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013468 newbuffer = PyUnicode_New(newlen, maxchar);
13469 if (newbuffer == NULL)
13470 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013471 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13472 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013473 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013474 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013475 }
13476 else {
13477 newbuffer = resize_compact(writer->buffer, newlen);
13478 if (newbuffer == NULL)
13479 return -1;
13480 }
13481 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013482 }
13483 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013484 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013485 newbuffer = PyUnicode_New(writer->size, maxchar);
13486 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013487 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013488 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13489 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013490 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013491 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013492 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013493 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013494
13495#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013496}
13497
Victor Stinnerca9381e2015-09-22 00:58:32 +020013498int
13499_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13500 enum PyUnicode_Kind kind)
13501{
13502 Py_UCS4 maxchar;
13503
13504 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13505 assert(writer->kind < kind);
13506
13507 switch (kind)
13508 {
13509 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13510 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13511 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13512 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013513 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013514 }
13515
13516 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13517}
13518
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013519static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013520_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013521{
Victor Stinner2740e462016-09-06 16:58:36 -070013522 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013523 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13524 return -1;
13525 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13526 writer->pos++;
13527 return 0;
13528}
13529
13530int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013531_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13532{
13533 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13534}
13535
13536int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013537_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13538{
13539 Py_UCS4 maxchar;
13540 Py_ssize_t len;
13541
13542 if (PyUnicode_READY(str) == -1)
13543 return -1;
13544 len = PyUnicode_GET_LENGTH(str);
13545 if (len == 0)
13546 return 0;
13547 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13548 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013549 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013550 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013551 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013552 Py_INCREF(str);
13553 writer->buffer = str;
13554 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013555 writer->pos += len;
13556 return 0;
13557 }
13558 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13559 return -1;
13560 }
13561 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13562 str, 0, len);
13563 writer->pos += len;
13564 return 0;
13565}
13566
Victor Stinnere215d962012-10-06 23:03:36 +020013567int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013568_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13569 Py_ssize_t start, Py_ssize_t end)
13570{
13571 Py_UCS4 maxchar;
13572 Py_ssize_t len;
13573
13574 if (PyUnicode_READY(str) == -1)
13575 return -1;
13576
13577 assert(0 <= start);
13578 assert(end <= PyUnicode_GET_LENGTH(str));
13579 assert(start <= end);
13580
13581 if (end == 0)
13582 return 0;
13583
13584 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13585 return _PyUnicodeWriter_WriteStr(writer, str);
13586
13587 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13588 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13589 else
13590 maxchar = writer->maxchar;
13591 len = end - start;
13592
13593 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13594 return -1;
13595
13596 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13597 str, start, len);
13598 writer->pos += len;
13599 return 0;
13600}
13601
13602int
Victor Stinner4a587072013-11-19 12:54:53 +010013603_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13604 const char *ascii, Py_ssize_t len)
13605{
13606 if (len == -1)
13607 len = strlen(ascii);
13608
13609 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13610
13611 if (writer->buffer == NULL && !writer->overallocate) {
13612 PyObject *str;
13613
13614 str = _PyUnicode_FromASCII(ascii, len);
13615 if (str == NULL)
13616 return -1;
13617
13618 writer->readonly = 1;
13619 writer->buffer = str;
13620 _PyUnicodeWriter_Update(writer);
13621 writer->pos += len;
13622 return 0;
13623 }
13624
13625 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13626 return -1;
13627
13628 switch (writer->kind)
13629 {
13630 case PyUnicode_1BYTE_KIND:
13631 {
13632 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13633 Py_UCS1 *data = writer->data;
13634
Christian Heimesf051e432016-09-13 20:22:02 +020013635 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013636 break;
13637 }
13638 case PyUnicode_2BYTE_KIND:
13639 {
13640 _PyUnicode_CONVERT_BYTES(
13641 Py_UCS1, Py_UCS2,
13642 ascii, ascii + len,
13643 (Py_UCS2 *)writer->data + writer->pos);
13644 break;
13645 }
13646 case PyUnicode_4BYTE_KIND:
13647 {
13648 _PyUnicode_CONVERT_BYTES(
13649 Py_UCS1, Py_UCS4,
13650 ascii, ascii + len,
13651 (Py_UCS4 *)writer->data + writer->pos);
13652 break;
13653 }
13654 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013655 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013656 }
13657
13658 writer->pos += len;
13659 return 0;
13660}
13661
13662int
13663_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13664 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013665{
13666 Py_UCS4 maxchar;
13667
13668 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13669 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13670 return -1;
13671 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13672 writer->pos += len;
13673 return 0;
13674}
13675
Victor Stinnerd3f08822012-05-29 12:57:52 +020013676PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013677_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013678{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013679 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013680
Victor Stinnerd3f08822012-05-29 12:57:52 +020013681 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013682 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013683 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013684 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013685
13686 str = writer->buffer;
13687 writer->buffer = NULL;
13688
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013689 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013690 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13691 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013692 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013693
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013694 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13695 PyObject *str2;
13696 str2 = resize_compact(str, writer->pos);
13697 if (str2 == NULL) {
13698 Py_DECREF(str);
13699 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013700 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013701 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013702 }
13703
Victor Stinner15a0bd32013-07-08 22:29:55 +020013704 assert(_PyUnicode_CheckConsistency(str, 1));
13705 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013706}
13707
Victor Stinnerd3f08822012-05-29 12:57:52 +020013708void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013709_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013710{
13711 Py_CLEAR(writer->buffer);
13712}
13713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013714#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013715
13716PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013717 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013718\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013719Return a formatted version of S, using substitutions from args and kwargs.\n\
13720The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013721
Eric Smith27bbca62010-11-04 17:06:58 +000013722PyDoc_STRVAR(format_map__doc__,
13723 "S.format_map(mapping) -> str\n\
13724\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013725Return a formatted version of S, using substitutions from mapping.\n\
13726The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013727
INADA Naoki3ae20562017-01-16 20:41:20 +090013728/*[clinic input]
13729str.__format__ as unicode___format__
13730
13731 format_spec: unicode
13732 /
13733
13734Return a formatted version of the string as described by format_spec.
13735[clinic start generated code]*/
13736
Eric Smith4a7d76d2008-05-30 18:10:19 +000013737static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013738unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013739/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013740{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013741 _PyUnicodeWriter writer;
13742 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013743
Victor Stinnerd3f08822012-05-29 12:57:52 +020013744 if (PyUnicode_READY(self) == -1)
13745 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013746 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013747 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13748 self, format_spec, 0,
13749 PyUnicode_GET_LENGTH(format_spec));
13750 if (ret == -1) {
13751 _PyUnicodeWriter_Dealloc(&writer);
13752 return NULL;
13753 }
13754 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013755}
13756
INADA Naoki3ae20562017-01-16 20:41:20 +090013757/*[clinic input]
13758str.__sizeof__ as unicode_sizeof
13759
13760Return the size of the string in memory, in bytes.
13761[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013762
13763static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013764unicode_sizeof_impl(PyObject *self)
13765/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013766{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013767 Py_ssize_t size;
13768
13769 /* If it's a compact object, account for base structure +
13770 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013771 if (PyUnicode_IS_COMPACT_ASCII(self))
13772 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13773 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013775 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013776 else {
13777 /* If it is a two-block object, account for base object, and
13778 for character block if present. */
13779 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013780 if (_PyUnicode_DATA_ANY(self))
13781 size += (PyUnicode_GET_LENGTH(self) + 1) *
13782 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013783 }
13784 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013785 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013786 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13787 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13788 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13789 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790
13791 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013792}
13793
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013794static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013795unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013796{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013797 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013798 if (!copy)
13799 return NULL;
13800 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013801}
13802
Guido van Rossumd57fd912000-03-10 22:53:23 +000013803static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013804 UNICODE_ENCODE_METHODDEF
13805 UNICODE_REPLACE_METHODDEF
13806 UNICODE_SPLIT_METHODDEF
13807 UNICODE_RSPLIT_METHODDEF
13808 UNICODE_JOIN_METHODDEF
13809 UNICODE_CAPITALIZE_METHODDEF
13810 UNICODE_CASEFOLD_METHODDEF
13811 UNICODE_TITLE_METHODDEF
13812 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013813 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013814 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013815 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013816 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013817 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013818 UNICODE_LJUST_METHODDEF
13819 UNICODE_LOWER_METHODDEF
13820 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013821 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13822 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013823 UNICODE_RJUST_METHODDEF
13824 UNICODE_RSTRIP_METHODDEF
13825 UNICODE_RPARTITION_METHODDEF
13826 UNICODE_SPLITLINES_METHODDEF
13827 UNICODE_STRIP_METHODDEF
13828 UNICODE_SWAPCASE_METHODDEF
13829 UNICODE_TRANSLATE_METHODDEF
13830 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013831 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13832 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013833 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013834 UNICODE_ISLOWER_METHODDEF
13835 UNICODE_ISUPPER_METHODDEF
13836 UNICODE_ISTITLE_METHODDEF
13837 UNICODE_ISSPACE_METHODDEF
13838 UNICODE_ISDECIMAL_METHODDEF
13839 UNICODE_ISDIGIT_METHODDEF
13840 UNICODE_ISNUMERIC_METHODDEF
13841 UNICODE_ISALPHA_METHODDEF
13842 UNICODE_ISALNUM_METHODDEF
13843 UNICODE_ISIDENTIFIER_METHODDEF
13844 UNICODE_ISPRINTABLE_METHODDEF
13845 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013846 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013847 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013848 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013849 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013850 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013851#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013852 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013853 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854#endif
13855
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013856 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013857 {NULL, NULL}
13858};
13859
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013860static PyObject *
13861unicode_mod(PyObject *v, PyObject *w)
13862{
Brian Curtindfc80e32011-08-10 20:28:54 -050013863 if (!PyUnicode_Check(v))
13864 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013866}
13867
13868static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013869 0, /*nb_add*/
13870 0, /*nb_subtract*/
13871 0, /*nb_multiply*/
13872 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013873};
13874
Guido van Rossumd57fd912000-03-10 22:53:23 +000013875static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013876 (lenfunc) unicode_length, /* sq_length */
13877 PyUnicode_Concat, /* sq_concat */
13878 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13879 (ssizeargfunc) unicode_getitem, /* sq_item */
13880 0, /* sq_slice */
13881 0, /* sq_ass_item */
13882 0, /* sq_ass_slice */
13883 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013884};
13885
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013886static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013887unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013889 if (PyUnicode_READY(self) == -1)
13890 return NULL;
13891
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013892 if (PyIndex_Check(item)) {
13893 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013894 if (i == -1 && PyErr_Occurred())
13895 return NULL;
13896 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013897 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013898 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013899 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013900 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013901 PyObject *result;
13902 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013903 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013904 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013905
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013906 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013907 return NULL;
13908 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013909 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13910 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013911
13912 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013913 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013914 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013915 slicelength == PyUnicode_GET_LENGTH(self)) {
13916 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013917 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013918 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013919 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013920 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013921 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013922 src_kind = PyUnicode_KIND(self);
13923 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013924 if (!PyUnicode_IS_ASCII(self)) {
13925 kind_limit = kind_maxchar_limit(src_kind);
13926 max_char = 0;
13927 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13928 ch = PyUnicode_READ(src_kind, src_data, cur);
13929 if (ch > max_char) {
13930 max_char = ch;
13931 if (max_char >= kind_limit)
13932 break;
13933 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013934 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013935 }
Victor Stinner55c99112011-10-13 01:17:06 +020013936 else
13937 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013938 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013939 if (result == NULL)
13940 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013941 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013942 dest_data = PyUnicode_DATA(result);
13943
13944 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013945 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13946 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013947 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013948 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013949 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013950 } else {
13951 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13952 return NULL;
13953 }
13954}
13955
13956static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 (lenfunc)unicode_length, /* mp_length */
13958 (binaryfunc)unicode_subscript, /* mp_subscript */
13959 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013960};
13961
Guido van Rossumd57fd912000-03-10 22:53:23 +000013962
Guido van Rossumd57fd912000-03-10 22:53:23 +000013963/* Helpers for PyUnicode_Format() */
13964
Victor Stinnera47082312012-10-04 02:19:54 +020013965struct unicode_formatter_t {
13966 PyObject *args;
13967 int args_owned;
13968 Py_ssize_t arglen, argidx;
13969 PyObject *dict;
13970
13971 enum PyUnicode_Kind fmtkind;
13972 Py_ssize_t fmtcnt, fmtpos;
13973 void *fmtdata;
13974 PyObject *fmtstr;
13975
13976 _PyUnicodeWriter writer;
13977};
13978
13979struct unicode_format_arg_t {
13980 Py_UCS4 ch;
13981 int flags;
13982 Py_ssize_t width;
13983 int prec;
13984 int sign;
13985};
13986
Guido van Rossumd57fd912000-03-10 22:53:23 +000013987static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013988unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013989{
Victor Stinnera47082312012-10-04 02:19:54 +020013990 Py_ssize_t argidx = ctx->argidx;
13991
13992 if (argidx < ctx->arglen) {
13993 ctx->argidx++;
13994 if (ctx->arglen < 0)
13995 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013996 else
Victor Stinnera47082312012-10-04 02:19:54 +020013997 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013998 }
13999 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014000 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014001 return NULL;
14002}
14003
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014004/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005
Victor Stinnera47082312012-10-04 02:19:54 +020014006/* Format a float into the writer if the writer is not NULL, or into *p_output
14007 otherwise.
14008
14009 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014010static int
Victor Stinnera47082312012-10-04 02:19:54 +020014011formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14012 PyObject **p_output,
14013 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014014{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014015 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014016 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014017 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014018 int prec;
14019 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014020
Guido van Rossumd57fd912000-03-10 22:53:23 +000014021 x = PyFloat_AsDouble(v);
14022 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014023 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014024
Victor Stinnera47082312012-10-04 02:19:54 +020014025 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014026 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014027 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014028
Victor Stinnera47082312012-10-04 02:19:54 +020014029 if (arg->flags & F_ALT)
14030 dtoa_flags = Py_DTSF_ALT;
14031 else
14032 dtoa_flags = 0;
14033 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014034 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014035 return -1;
14036 len = strlen(p);
14037 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014038 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014039 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014040 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014041 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014042 }
14043 else
14044 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014045 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014046 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014047}
14048
Victor Stinnerd0880d52012-04-27 23:40:13 +020014049/* formatlong() emulates the format codes d, u, o, x and X, and
14050 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14051 * Python's regular ints.
14052 * Return value: a new PyUnicodeObject*, or NULL if error.
14053 * The output string is of the form
14054 * "-"? ("0x" | "0X")? digit+
14055 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14056 * set in flags. The case of hex digits will be correct,
14057 * There will be at least prec digits, zero-filled on the left if
14058 * necessary to get that many.
14059 * val object to be converted
14060 * flags bitmask of format flags; only F_ALT is looked at
14061 * prec minimum number of digits; 0-fill on left if needed
14062 * type a character in [duoxX]; u acts the same as d
14063 *
14064 * CAUTION: o, x and X conversions on regular ints can never
14065 * produce a '-' sign, but can for Python's unbounded ints.
14066 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014067PyObject *
14068_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014069{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014070 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014071 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014072 Py_ssize_t i;
14073 int sign; /* 1 if '-', else 0 */
14074 int len; /* number of characters */
14075 Py_ssize_t llen;
14076 int numdigits; /* len == numnondigits + numdigits */
14077 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014078
Victor Stinnerd0880d52012-04-27 23:40:13 +020014079 /* Avoid exceeding SSIZE_T_MAX */
14080 if (prec > INT_MAX-3) {
14081 PyErr_SetString(PyExc_OverflowError,
14082 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014084 }
14085
14086 assert(PyLong_Check(val));
14087
14088 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014089 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014090 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014091 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014092 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014093 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014094 /* int and int subclasses should print numerically when a numeric */
14095 /* format code is used (see issue18780) */
14096 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014097 break;
14098 case 'o':
14099 numnondigits = 2;
14100 result = PyNumber_ToBase(val, 8);
14101 break;
14102 case 'x':
14103 case 'X':
14104 numnondigits = 2;
14105 result = PyNumber_ToBase(val, 16);
14106 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014107 }
14108 if (!result)
14109 return NULL;
14110
14111 assert(unicode_modifiable(result));
14112 assert(PyUnicode_IS_READY(result));
14113 assert(PyUnicode_IS_ASCII(result));
14114
14115 /* To modify the string in-place, there can only be one reference. */
14116 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014117 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014118 PyErr_BadInternalCall();
14119 return NULL;
14120 }
14121 buf = PyUnicode_DATA(result);
14122 llen = PyUnicode_GET_LENGTH(result);
14123 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014124 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014125 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014126 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014127 return NULL;
14128 }
14129 len = (int)llen;
14130 sign = buf[0] == '-';
14131 numnondigits += sign;
14132 numdigits = len - numnondigits;
14133 assert(numdigits > 0);
14134
14135 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014136 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014137 (type == 'o' || type == 'x' || type == 'X'))) {
14138 assert(buf[sign] == '0');
14139 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14140 buf[sign+1] == 'o');
14141 numnondigits -= 2;
14142 buf += 2;
14143 len -= 2;
14144 if (sign)
14145 buf[0] = '-';
14146 assert(len == numnondigits + numdigits);
14147 assert(numdigits > 0);
14148 }
14149
14150 /* Fill with leading zeroes to meet minimum width. */
14151 if (prec > numdigits) {
14152 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14153 numnondigits + prec);
14154 char *b1;
14155 if (!r1) {
14156 Py_DECREF(result);
14157 return NULL;
14158 }
14159 b1 = PyBytes_AS_STRING(r1);
14160 for (i = 0; i < numnondigits; ++i)
14161 *b1++ = *buf++;
14162 for (i = 0; i < prec - numdigits; i++)
14163 *b1++ = '0';
14164 for (i = 0; i < numdigits; i++)
14165 *b1++ = *buf++;
14166 *b1 = '\0';
14167 Py_DECREF(result);
14168 result = r1;
14169 buf = PyBytes_AS_STRING(result);
14170 len = numnondigits + prec;
14171 }
14172
14173 /* Fix up case for hex conversions. */
14174 if (type == 'X') {
14175 /* Need to convert all lower case letters to upper case.
14176 and need to convert 0x to 0X (and -0x to -0X). */
14177 for (i = 0; i < len; i++)
14178 if (buf[i] >= 'a' && buf[i] <= 'x')
14179 buf[i] -= 'a'-'A';
14180 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014181 if (!PyUnicode_Check(result)
14182 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014183 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014184 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014185 Py_DECREF(result);
14186 result = unicode;
14187 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014188 else if (len != PyUnicode_GET_LENGTH(result)) {
14189 if (PyUnicode_Resize(&result, len) < 0)
14190 Py_CLEAR(result);
14191 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014192 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014193}
14194
Ethan Furmandf3ed242014-01-05 06:50:30 -080014195/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014196 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014197 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014198 * -1 and raise an exception on error */
14199static int
Victor Stinnera47082312012-10-04 02:19:54 +020014200mainformatlong(PyObject *v,
14201 struct unicode_format_arg_t *arg,
14202 PyObject **p_output,
14203 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014204{
14205 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014206 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014207
14208 if (!PyNumber_Check(v))
14209 goto wrongtype;
14210
Ethan Furman9ab74802014-03-21 06:38:46 -070014211 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014212 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014213 if (type == 'o' || type == 'x' || type == 'X') {
14214 iobj = PyNumber_Index(v);
14215 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014216 if (PyErr_ExceptionMatches(PyExc_TypeError))
14217 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014218 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014219 }
14220 }
14221 else {
14222 iobj = PyNumber_Long(v);
14223 if (iobj == NULL ) {
14224 if (PyErr_ExceptionMatches(PyExc_TypeError))
14225 goto wrongtype;
14226 return -1;
14227 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014228 }
14229 assert(PyLong_Check(iobj));
14230 }
14231 else {
14232 iobj = v;
14233 Py_INCREF(iobj);
14234 }
14235
14236 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014237 && arg->width == -1 && arg->prec == -1
14238 && !(arg->flags & (F_SIGN | F_BLANK))
14239 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014240 {
14241 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014242 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014243 int base;
14244
Victor Stinnera47082312012-10-04 02:19:54 +020014245 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014246 {
14247 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014248 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 case 'd':
14250 case 'i':
14251 case 'u':
14252 base = 10;
14253 break;
14254 case 'o':
14255 base = 8;
14256 break;
14257 case 'x':
14258 case 'X':
14259 base = 16;
14260 break;
14261 }
14262
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014263 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14264 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014265 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014266 }
14267 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014268 return 1;
14269 }
14270
Ethan Furmanb95b5612015-01-23 20:05:18 -080014271 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014272 Py_DECREF(iobj);
14273 if (res == NULL)
14274 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014275 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014276 return 0;
14277
14278wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014279 switch(type)
14280 {
14281 case 'o':
14282 case 'x':
14283 case 'X':
14284 PyErr_Format(PyExc_TypeError,
14285 "%%%c format: an integer is required, "
14286 "not %.200s",
14287 type, Py_TYPE(v)->tp_name);
14288 break;
14289 default:
14290 PyErr_Format(PyExc_TypeError,
14291 "%%%c format: a number is required, "
14292 "not %.200s",
14293 type, Py_TYPE(v)->tp_name);
14294 break;
14295 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014296 return -1;
14297}
14298
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014299static Py_UCS4
14300formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014301{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014302 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014303 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014304 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014305 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014306 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014307 goto onError;
14308 }
14309 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014310 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014311 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014312 /* make sure number is a type of integer */
14313 if (!PyLong_Check(v)) {
14314 iobj = PyNumber_Index(v);
14315 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014316 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014317 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014318 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014319 Py_DECREF(iobj);
14320 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014321 else {
14322 x = PyLong_AsLong(v);
14323 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014324 if (x == -1 && PyErr_Occurred())
14325 goto onError;
14326
Victor Stinner8faf8212011-12-08 22:14:11 +010014327 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014328 PyErr_SetString(PyExc_OverflowError,
14329 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014330 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014331 }
14332
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014333 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014334 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014335
Benjamin Peterson29060642009-01-31 22:14:21 +000014336 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014337 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014338 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014339 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014340}
14341
Victor Stinnera47082312012-10-04 02:19:54 +020014342/* Parse options of an argument: flags, width, precision.
14343 Handle also "%(name)" syntax.
14344
14345 Return 0 if the argument has been formatted into arg->str.
14346 Return 1 if the argument has been written into ctx->writer,
14347 Raise an exception and return -1 on error. */
14348static int
14349unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14350 struct unicode_format_arg_t *arg)
14351{
14352#define FORMAT_READ(ctx) \
14353 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14354
14355 PyObject *v;
14356
Victor Stinnera47082312012-10-04 02:19:54 +020014357 if (arg->ch == '(') {
14358 /* Get argument value from a dictionary. Example: "%(name)s". */
14359 Py_ssize_t keystart;
14360 Py_ssize_t keylen;
14361 PyObject *key;
14362 int pcount = 1;
14363
14364 if (ctx->dict == NULL) {
14365 PyErr_SetString(PyExc_TypeError,
14366 "format requires a mapping");
14367 return -1;
14368 }
14369 ++ctx->fmtpos;
14370 --ctx->fmtcnt;
14371 keystart = ctx->fmtpos;
14372 /* Skip over balanced parentheses */
14373 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14374 arg->ch = FORMAT_READ(ctx);
14375 if (arg->ch == ')')
14376 --pcount;
14377 else if (arg->ch == '(')
14378 ++pcount;
14379 ctx->fmtpos++;
14380 }
14381 keylen = ctx->fmtpos - keystart - 1;
14382 if (ctx->fmtcnt < 0 || pcount > 0) {
14383 PyErr_SetString(PyExc_ValueError,
14384 "incomplete format key");
14385 return -1;
14386 }
14387 key = PyUnicode_Substring(ctx->fmtstr,
14388 keystart, keystart + keylen);
14389 if (key == NULL)
14390 return -1;
14391 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014392 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014393 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014394 }
14395 ctx->args = PyObject_GetItem(ctx->dict, key);
14396 Py_DECREF(key);
14397 if (ctx->args == NULL)
14398 return -1;
14399 ctx->args_owned = 1;
14400 ctx->arglen = -1;
14401 ctx->argidx = -2;
14402 }
14403
14404 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014405 while (--ctx->fmtcnt >= 0) {
14406 arg->ch = FORMAT_READ(ctx);
14407 ctx->fmtpos++;
14408 switch (arg->ch) {
14409 case '-': arg->flags |= F_LJUST; continue;
14410 case '+': arg->flags |= F_SIGN; continue;
14411 case ' ': arg->flags |= F_BLANK; continue;
14412 case '#': arg->flags |= F_ALT; continue;
14413 case '0': arg->flags |= F_ZERO; continue;
14414 }
14415 break;
14416 }
14417
14418 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014419 if (arg->ch == '*') {
14420 v = unicode_format_getnextarg(ctx);
14421 if (v == NULL)
14422 return -1;
14423 if (!PyLong_Check(v)) {
14424 PyErr_SetString(PyExc_TypeError,
14425 "* wants int");
14426 return -1;
14427 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014428 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014429 if (arg->width == -1 && PyErr_Occurred())
14430 return -1;
14431 if (arg->width < 0) {
14432 arg->flags |= F_LJUST;
14433 arg->width = -arg->width;
14434 }
14435 if (--ctx->fmtcnt >= 0) {
14436 arg->ch = FORMAT_READ(ctx);
14437 ctx->fmtpos++;
14438 }
14439 }
14440 else if (arg->ch >= '0' && arg->ch <= '9') {
14441 arg->width = arg->ch - '0';
14442 while (--ctx->fmtcnt >= 0) {
14443 arg->ch = FORMAT_READ(ctx);
14444 ctx->fmtpos++;
14445 if (arg->ch < '0' || arg->ch > '9')
14446 break;
14447 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14448 mixing signed and unsigned comparison. Since arg->ch is between
14449 '0' and '9', casting to int is safe. */
14450 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14451 PyErr_SetString(PyExc_ValueError,
14452 "width too big");
14453 return -1;
14454 }
14455 arg->width = arg->width*10 + (arg->ch - '0');
14456 }
14457 }
14458
14459 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014460 if (arg->ch == '.') {
14461 arg->prec = 0;
14462 if (--ctx->fmtcnt >= 0) {
14463 arg->ch = FORMAT_READ(ctx);
14464 ctx->fmtpos++;
14465 }
14466 if (arg->ch == '*') {
14467 v = unicode_format_getnextarg(ctx);
14468 if (v == NULL)
14469 return -1;
14470 if (!PyLong_Check(v)) {
14471 PyErr_SetString(PyExc_TypeError,
14472 "* wants int");
14473 return -1;
14474 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014475 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014476 if (arg->prec == -1 && PyErr_Occurred())
14477 return -1;
14478 if (arg->prec < 0)
14479 arg->prec = 0;
14480 if (--ctx->fmtcnt >= 0) {
14481 arg->ch = FORMAT_READ(ctx);
14482 ctx->fmtpos++;
14483 }
14484 }
14485 else if (arg->ch >= '0' && arg->ch <= '9') {
14486 arg->prec = arg->ch - '0';
14487 while (--ctx->fmtcnt >= 0) {
14488 arg->ch = FORMAT_READ(ctx);
14489 ctx->fmtpos++;
14490 if (arg->ch < '0' || arg->ch > '9')
14491 break;
14492 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14493 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014494 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014495 return -1;
14496 }
14497 arg->prec = arg->prec*10 + (arg->ch - '0');
14498 }
14499 }
14500 }
14501
14502 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14503 if (ctx->fmtcnt >= 0) {
14504 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14505 if (--ctx->fmtcnt >= 0) {
14506 arg->ch = FORMAT_READ(ctx);
14507 ctx->fmtpos++;
14508 }
14509 }
14510 }
14511 if (ctx->fmtcnt < 0) {
14512 PyErr_SetString(PyExc_ValueError,
14513 "incomplete format");
14514 return -1;
14515 }
14516 return 0;
14517
14518#undef FORMAT_READ
14519}
14520
14521/* Format one argument. Supported conversion specifiers:
14522
14523 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014524 - "i", "d", "u": int or float
14525 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014526 - "e", "E", "f", "F", "g", "G": float
14527 - "c": int or str (1 character)
14528
Victor Stinner8dbd4212012-12-04 09:30:24 +010014529 When possible, the output is written directly into the Unicode writer
14530 (ctx->writer). A string is created when padding is required.
14531
Victor Stinnera47082312012-10-04 02:19:54 +020014532 Return 0 if the argument has been formatted into *p_str,
14533 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014534 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014535static int
14536unicode_format_arg_format(struct unicode_formatter_t *ctx,
14537 struct unicode_format_arg_t *arg,
14538 PyObject **p_str)
14539{
14540 PyObject *v;
14541 _PyUnicodeWriter *writer = &ctx->writer;
14542
14543 if (ctx->fmtcnt == 0)
14544 ctx->writer.overallocate = 0;
14545
Victor Stinnera47082312012-10-04 02:19:54 +020014546 v = unicode_format_getnextarg(ctx);
14547 if (v == NULL)
14548 return -1;
14549
Victor Stinnera47082312012-10-04 02:19:54 +020014550
14551 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014552 case 's':
14553 case 'r':
14554 case 'a':
14555 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14556 /* Fast path */
14557 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14558 return -1;
14559 return 1;
14560 }
14561
14562 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14563 *p_str = v;
14564 Py_INCREF(*p_str);
14565 }
14566 else {
14567 if (arg->ch == 's')
14568 *p_str = PyObject_Str(v);
14569 else if (arg->ch == 'r')
14570 *p_str = PyObject_Repr(v);
14571 else
14572 *p_str = PyObject_ASCII(v);
14573 }
14574 break;
14575
14576 case 'i':
14577 case 'd':
14578 case 'u':
14579 case 'o':
14580 case 'x':
14581 case 'X':
14582 {
14583 int ret = mainformatlong(v, arg, p_str, writer);
14584 if (ret != 0)
14585 return ret;
14586 arg->sign = 1;
14587 break;
14588 }
14589
14590 case 'e':
14591 case 'E':
14592 case 'f':
14593 case 'F':
14594 case 'g':
14595 case 'G':
14596 if (arg->width == -1 && arg->prec == -1
14597 && !(arg->flags & (F_SIGN | F_BLANK)))
14598 {
14599 /* Fast path */
14600 if (formatfloat(v, arg, NULL, writer) == -1)
14601 return -1;
14602 return 1;
14603 }
14604
14605 arg->sign = 1;
14606 if (formatfloat(v, arg, p_str, NULL) == -1)
14607 return -1;
14608 break;
14609
14610 case 'c':
14611 {
14612 Py_UCS4 ch = formatchar(v);
14613 if (ch == (Py_UCS4) -1)
14614 return -1;
14615 if (arg->width == -1 && arg->prec == -1) {
14616 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014617 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014618 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014619 return 1;
14620 }
14621 *p_str = PyUnicode_FromOrdinal(ch);
14622 break;
14623 }
14624
14625 default:
14626 PyErr_Format(PyExc_ValueError,
14627 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014628 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014629 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14630 (int)arg->ch,
14631 ctx->fmtpos - 1);
14632 return -1;
14633 }
14634 if (*p_str == NULL)
14635 return -1;
14636 assert (PyUnicode_Check(*p_str));
14637 return 0;
14638}
14639
14640static int
14641unicode_format_arg_output(struct unicode_formatter_t *ctx,
14642 struct unicode_format_arg_t *arg,
14643 PyObject *str)
14644{
14645 Py_ssize_t len;
14646 enum PyUnicode_Kind kind;
14647 void *pbuf;
14648 Py_ssize_t pindex;
14649 Py_UCS4 signchar;
14650 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014651 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014652 Py_ssize_t sublen;
14653 _PyUnicodeWriter *writer = &ctx->writer;
14654 Py_UCS4 fill;
14655
14656 fill = ' ';
14657 if (arg->sign && arg->flags & F_ZERO)
14658 fill = '0';
14659
14660 if (PyUnicode_READY(str) == -1)
14661 return -1;
14662
14663 len = PyUnicode_GET_LENGTH(str);
14664 if ((arg->width == -1 || arg->width <= len)
14665 && (arg->prec == -1 || arg->prec >= len)
14666 && !(arg->flags & (F_SIGN | F_BLANK)))
14667 {
14668 /* Fast path */
14669 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14670 return -1;
14671 return 0;
14672 }
14673
14674 /* Truncate the string for "s", "r" and "a" formats
14675 if the precision is set */
14676 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14677 if (arg->prec >= 0 && len > arg->prec)
14678 len = arg->prec;
14679 }
14680
14681 /* Adjust sign and width */
14682 kind = PyUnicode_KIND(str);
14683 pbuf = PyUnicode_DATA(str);
14684 pindex = 0;
14685 signchar = '\0';
14686 if (arg->sign) {
14687 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14688 if (ch == '-' || ch == '+') {
14689 signchar = ch;
14690 len--;
14691 pindex++;
14692 }
14693 else if (arg->flags & F_SIGN)
14694 signchar = '+';
14695 else if (arg->flags & F_BLANK)
14696 signchar = ' ';
14697 else
14698 arg->sign = 0;
14699 }
14700 if (arg->width < len)
14701 arg->width = len;
14702
14703 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014704 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014705 if (!(arg->flags & F_LJUST)) {
14706 if (arg->sign) {
14707 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014708 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014709 }
14710 else {
14711 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014712 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014713 }
14714 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014715 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14716 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014717 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014718 }
14719
Victor Stinnera47082312012-10-04 02:19:54 +020014720 buflen = arg->width;
14721 if (arg->sign && len == arg->width)
14722 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014723 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014724 return -1;
14725
14726 /* Write the sign if needed */
14727 if (arg->sign) {
14728 if (fill != ' ') {
14729 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14730 writer->pos += 1;
14731 }
14732 if (arg->width > len)
14733 arg->width--;
14734 }
14735
14736 /* Write the numeric prefix for "x", "X" and "o" formats
14737 if the alternate form is used.
14738 For example, write "0x" for the "%#x" format. */
14739 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14740 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14741 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14742 if (fill != ' ') {
14743 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14744 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14745 writer->pos += 2;
14746 pindex += 2;
14747 }
14748 arg->width -= 2;
14749 if (arg->width < 0)
14750 arg->width = 0;
14751 len -= 2;
14752 }
14753
14754 /* Pad left with the fill character if needed */
14755 if (arg->width > len && !(arg->flags & F_LJUST)) {
14756 sublen = arg->width - len;
14757 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14758 writer->pos += sublen;
14759 arg->width = len;
14760 }
14761
14762 /* If padding with spaces: write sign if needed and/or numeric prefix if
14763 the alternate form is used */
14764 if (fill == ' ') {
14765 if (arg->sign) {
14766 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14767 writer->pos += 1;
14768 }
14769 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14770 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14771 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14772 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14773 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14774 writer->pos += 2;
14775 pindex += 2;
14776 }
14777 }
14778
14779 /* Write characters */
14780 if (len) {
14781 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14782 str, pindex, len);
14783 writer->pos += len;
14784 }
14785
14786 /* Pad right with the fill character if needed */
14787 if (arg->width > len) {
14788 sublen = arg->width - len;
14789 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14790 writer->pos += sublen;
14791 }
14792 return 0;
14793}
14794
14795/* Helper of PyUnicode_Format(): format one arg.
14796 Return 0 on success, raise an exception and return -1 on error. */
14797static int
14798unicode_format_arg(struct unicode_formatter_t *ctx)
14799{
14800 struct unicode_format_arg_t arg;
14801 PyObject *str;
14802 int ret;
14803
Victor Stinner8dbd4212012-12-04 09:30:24 +010014804 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014805 if (arg.ch == '%') {
14806 ctx->fmtpos++;
14807 ctx->fmtcnt--;
14808 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14809 return -1;
14810 return 0;
14811 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014812 arg.flags = 0;
14813 arg.width = -1;
14814 arg.prec = -1;
14815 arg.sign = 0;
14816 str = NULL;
14817
Victor Stinnera47082312012-10-04 02:19:54 +020014818 ret = unicode_format_arg_parse(ctx, &arg);
14819 if (ret == -1)
14820 return -1;
14821
14822 ret = unicode_format_arg_format(ctx, &arg, &str);
14823 if (ret == -1)
14824 return -1;
14825
14826 if (ret != 1) {
14827 ret = unicode_format_arg_output(ctx, &arg, str);
14828 Py_DECREF(str);
14829 if (ret == -1)
14830 return -1;
14831 }
14832
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014833 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014834 PyErr_SetString(PyExc_TypeError,
14835 "not all arguments converted during string formatting");
14836 return -1;
14837 }
14838 return 0;
14839}
14840
Alexander Belopolsky40018472011-02-26 01:02:56 +000014841PyObject *
14842PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014843{
Victor Stinnera47082312012-10-04 02:19:54 +020014844 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014845
Guido van Rossumd57fd912000-03-10 22:53:23 +000014846 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014847 PyErr_BadInternalCall();
14848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014849 }
Victor Stinnera47082312012-10-04 02:19:54 +020014850
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014851 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014852 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014853
14854 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014855 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14856 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14857 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14858 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014859
Victor Stinner8f674cc2013-04-17 23:02:17 +020014860 _PyUnicodeWriter_Init(&ctx.writer);
14861 ctx.writer.min_length = ctx.fmtcnt + 100;
14862 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014863
Guido van Rossumd57fd912000-03-10 22:53:23 +000014864 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014865 ctx.arglen = PyTuple_Size(args);
14866 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014867 }
14868 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014869 ctx.arglen = -1;
14870 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014871 }
Victor Stinnera47082312012-10-04 02:19:54 +020014872 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014873 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014874 ctx.dict = args;
14875 else
14876 ctx.dict = NULL;
14877 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014878
Victor Stinnera47082312012-10-04 02:19:54 +020014879 while (--ctx.fmtcnt >= 0) {
14880 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014881 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014882
14883 nonfmtpos = ctx.fmtpos++;
14884 while (ctx.fmtcnt >= 0 &&
14885 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14886 ctx.fmtpos++;
14887 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014888 }
Victor Stinnera47082312012-10-04 02:19:54 +020014889 if (ctx.fmtcnt < 0) {
14890 ctx.fmtpos--;
14891 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014892 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014893
Victor Stinnercfc4c132013-04-03 01:48:39 +020014894 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14895 nonfmtpos, ctx.fmtpos) < 0)
14896 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014897 }
14898 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014899 ctx.fmtpos++;
14900 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014901 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014902 }
14903 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014904
Victor Stinnera47082312012-10-04 02:19:54 +020014905 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014906 PyErr_SetString(PyExc_TypeError,
14907 "not all arguments converted during string formatting");
14908 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014909 }
14910
Victor Stinnera47082312012-10-04 02:19:54 +020014911 if (ctx.args_owned) {
14912 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014913 }
Victor Stinnera47082312012-10-04 02:19:54 +020014914 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014915
Benjamin Peterson29060642009-01-31 22:14:21 +000014916 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014917 _PyUnicodeWriter_Dealloc(&ctx.writer);
14918 if (ctx.args_owned) {
14919 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014920 }
14921 return NULL;
14922}
14923
Jeremy Hylton938ace62002-07-17 16:30:39 +000014924static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014925unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14926
Tim Peters6d6c1a32001-08-02 04:15:00 +000014927static PyObject *
14928unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14929{
Benjamin Peterson29060642009-01-31 22:14:21 +000014930 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014931 static char *kwlist[] = {"object", "encoding", "errors", 0};
14932 char *encoding = NULL;
14933 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014934
Benjamin Peterson14339b62009-01-31 16:36:08 +000014935 if (type != &PyUnicode_Type)
14936 return unicode_subtype_new(type, args, kwds);
14937 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014938 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014939 return NULL;
14940 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014941 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014942 if (encoding == NULL && errors == NULL)
14943 return PyObject_Str(x);
14944 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014945 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014946}
14947
Guido van Rossume023fe02001-08-30 03:12:59 +000014948static PyObject *
14949unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14950{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014951 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014952 Py_ssize_t length, char_size;
14953 int share_wstr, share_utf8;
14954 unsigned int kind;
14955 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014956
Benjamin Peterson14339b62009-01-31 16:36:08 +000014957 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014958
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014959 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014960 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014961 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014962 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014963 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014964 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014965 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014966 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014967
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014968 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014969 if (self == NULL) {
14970 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014971 return NULL;
14972 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014973 kind = PyUnicode_KIND(unicode);
14974 length = PyUnicode_GET_LENGTH(unicode);
14975
14976 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014977#ifdef Py_DEBUG
14978 _PyUnicode_HASH(self) = -1;
14979#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014980 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014981#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014982 _PyUnicode_STATE(self).interned = 0;
14983 _PyUnicode_STATE(self).kind = kind;
14984 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014985 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014986 _PyUnicode_STATE(self).ready = 1;
14987 _PyUnicode_WSTR(self) = NULL;
14988 _PyUnicode_UTF8_LENGTH(self) = 0;
14989 _PyUnicode_UTF8(self) = NULL;
14990 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014991 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014992
14993 share_utf8 = 0;
14994 share_wstr = 0;
14995 if (kind == PyUnicode_1BYTE_KIND) {
14996 char_size = 1;
14997 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14998 share_utf8 = 1;
14999 }
15000 else if (kind == PyUnicode_2BYTE_KIND) {
15001 char_size = 2;
15002 if (sizeof(wchar_t) == 2)
15003 share_wstr = 1;
15004 }
15005 else {
15006 assert(kind == PyUnicode_4BYTE_KIND);
15007 char_size = 4;
15008 if (sizeof(wchar_t) == 4)
15009 share_wstr = 1;
15010 }
15011
15012 /* Ensure we won't overflow the length. */
15013 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15014 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015015 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015016 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015017 data = PyObject_MALLOC((length + 1) * char_size);
15018 if (data == NULL) {
15019 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015020 goto onError;
15021 }
15022
Victor Stinnerc3c74152011-10-02 20:39:55 +020015023 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015024 if (share_utf8) {
15025 _PyUnicode_UTF8_LENGTH(self) = length;
15026 _PyUnicode_UTF8(self) = data;
15027 }
15028 if (share_wstr) {
15029 _PyUnicode_WSTR_LENGTH(self) = length;
15030 _PyUnicode_WSTR(self) = (wchar_t *)data;
15031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015032
Christian Heimesf051e432016-09-13 20:22:02 +020015033 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015034 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015035 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015036#ifdef Py_DEBUG
15037 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15038#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015039 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015040 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015041
15042onError:
15043 Py_DECREF(unicode);
15044 Py_DECREF(self);
15045 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015046}
15047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015048PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015049"str(object='') -> str\n\
15050str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015051\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015052Create a new string object from the given object. If encoding or\n\
15053errors is specified, then the object must expose a data buffer\n\
15054that will be decoded using the given encoding and error handler.\n\
15055Otherwise, returns the result of object.__str__() (if defined)\n\
15056or repr(object).\n\
15057encoding defaults to sys.getdefaultencoding().\n\
15058errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015059
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015060static PyObject *unicode_iter(PyObject *seq);
15061
Guido van Rossumd57fd912000-03-10 22:53:23 +000015062PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015063 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015064 "str", /* tp_name */
15065 sizeof(PyUnicodeObject), /* tp_size */
15066 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015067 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015068 (destructor)unicode_dealloc, /* tp_dealloc */
15069 0, /* tp_print */
15070 0, /* tp_getattr */
15071 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015072 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015073 unicode_repr, /* tp_repr */
15074 &unicode_as_number, /* tp_as_number */
15075 &unicode_as_sequence, /* tp_as_sequence */
15076 &unicode_as_mapping, /* tp_as_mapping */
15077 (hashfunc) unicode_hash, /* tp_hash*/
15078 0, /* tp_call*/
15079 (reprfunc) unicode_str, /* tp_str */
15080 PyObject_GenericGetAttr, /* tp_getattro */
15081 0, /* tp_setattro */
15082 0, /* tp_as_buffer */
15083 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015084 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015085 unicode_doc, /* tp_doc */
15086 0, /* tp_traverse */
15087 0, /* tp_clear */
15088 PyUnicode_RichCompare, /* tp_richcompare */
15089 0, /* tp_weaklistoffset */
15090 unicode_iter, /* tp_iter */
15091 0, /* tp_iternext */
15092 unicode_methods, /* tp_methods */
15093 0, /* tp_members */
15094 0, /* tp_getset */
15095 &PyBaseObject_Type, /* tp_base */
15096 0, /* tp_dict */
15097 0, /* tp_descr_get */
15098 0, /* tp_descr_set */
15099 0, /* tp_dictoffset */
15100 0, /* tp_init */
15101 0, /* tp_alloc */
15102 unicode_new, /* tp_new */
15103 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015104};
15105
15106/* Initialize the Unicode implementation */
15107
Victor Stinner3a50e702011-10-18 21:21:00 +020015108int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015109{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015110 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015111 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015112 0x000A, /* LINE FEED */
15113 0x000D, /* CARRIAGE RETURN */
15114 0x001C, /* FILE SEPARATOR */
15115 0x001D, /* GROUP SEPARATOR */
15116 0x001E, /* RECORD SEPARATOR */
15117 0x0085, /* NEXT LINE */
15118 0x2028, /* LINE SEPARATOR */
15119 0x2029, /* PARAGRAPH SEPARATOR */
15120 };
15121
Fred Drakee4315f52000-05-09 19:53:39 +000015122 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015123 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015124 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015125 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015126 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015127
Guido van Rossumcacfc072002-05-24 19:01:59 +000015128 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015129 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015130
15131 /* initialize the linebreak bloom filter */
15132 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015133 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015134 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015135
Christian Heimes26532f72013-07-20 14:57:16 +020015136 if (PyType_Ready(&EncodingMapType) < 0)
15137 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015138
Benjamin Petersonc4311282012-10-30 23:21:10 -040015139 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15140 Py_FatalError("Can't initialize field name iterator type");
15141
15142 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15143 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015144
Victor Stinner3a50e702011-10-18 21:21:00 +020015145 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015146}
15147
15148/* Finalize the Unicode implementation */
15149
Christian Heimesa156e092008-02-16 07:38:31 +000015150int
15151PyUnicode_ClearFreeList(void)
15152{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015153 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015154}
15155
Guido van Rossumd57fd912000-03-10 22:53:23 +000015156void
Thomas Wouters78890102000-07-22 19:25:51 +000015157_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015158{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015159 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015160
Serhiy Storchaka05997252013-01-26 12:14:02 +020015161 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015162
Serhiy Storchaka05997252013-01-26 12:14:02 +020015163 for (i = 0; i < 256; i++)
15164 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015165 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015166 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015167}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015168
Walter Dörwald16807132007-05-25 13:52:07 +000015169void
15170PyUnicode_InternInPlace(PyObject **p)
15171{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015172 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015173 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015174#ifdef Py_DEBUG
15175 assert(s != NULL);
15176 assert(_PyUnicode_CHECK(s));
15177#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015179 return;
15180#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015181 /* If it's a subclass, we don't really know what putting
15182 it in the interned dict might do. */
15183 if (!PyUnicode_CheckExact(s))
15184 return;
15185 if (PyUnicode_CHECK_INTERNED(s))
15186 return;
15187 if (interned == NULL) {
15188 interned = PyDict_New();
15189 if (interned == NULL) {
15190 PyErr_Clear(); /* Don't leave an exception */
15191 return;
15192 }
15193 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015194 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015195 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015196 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015197 if (t == NULL) {
15198 PyErr_Clear();
15199 return;
15200 }
15201 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015202 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015203 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015204 return;
15205 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015206 /* The two references in interned are not counted by refcnt.
15207 The deallocator will take care of this */
15208 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015209 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015210}
15211
15212void
15213PyUnicode_InternImmortal(PyObject **p)
15214{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 PyUnicode_InternInPlace(p);
15216 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015217 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015218 Py_INCREF(*p);
15219 }
Walter Dörwald16807132007-05-25 13:52:07 +000015220}
15221
15222PyObject *
15223PyUnicode_InternFromString(const char *cp)
15224{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015225 PyObject *s = PyUnicode_FromString(cp);
15226 if (s == NULL)
15227 return NULL;
15228 PyUnicode_InternInPlace(&s);
15229 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015230}
15231
Alexander Belopolsky40018472011-02-26 01:02:56 +000015232void
15233_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015234{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015235 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015236 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015237 Py_ssize_t i, n;
15238 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015239
Benjamin Peterson14339b62009-01-31 16:36:08 +000015240 if (interned == NULL || !PyDict_Check(interned))
15241 return;
15242 keys = PyDict_Keys(interned);
15243 if (keys == NULL || !PyList_Check(keys)) {
15244 PyErr_Clear();
15245 return;
15246 }
Walter Dörwald16807132007-05-25 13:52:07 +000015247
Benjamin Peterson14339b62009-01-31 16:36:08 +000015248 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15249 detector, interned unicode strings are not forcibly deallocated;
15250 rather, we give them their stolen references back, and then clear
15251 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015252
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 n = PyList_GET_SIZE(keys);
15254 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015255 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015256 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015257 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015258 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015259 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015260 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015261 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015262 case SSTATE_NOT_INTERNED:
15263 /* XXX Shouldn't happen */
15264 break;
15265 case SSTATE_INTERNED_IMMORTAL:
15266 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015267 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 break;
15269 case SSTATE_INTERNED_MORTAL:
15270 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015271 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015272 break;
15273 default:
15274 Py_FatalError("Inconsistent interned string state.");
15275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015276 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 }
15278 fprintf(stderr, "total size of all interned strings: "
15279 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15280 "mortal/immortal\n", mortal_size, immortal_size);
15281 Py_DECREF(keys);
15282 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015283 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015284}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015285
15286
15287/********************* Unicode Iterator **************************/
15288
15289typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015290 PyObject_HEAD
15291 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015292 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015293} unicodeiterobject;
15294
15295static void
15296unicodeiter_dealloc(unicodeiterobject *it)
15297{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015298 _PyObject_GC_UNTRACK(it);
15299 Py_XDECREF(it->it_seq);
15300 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015301}
15302
15303static int
15304unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15305{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 Py_VISIT(it->it_seq);
15307 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015308}
15309
15310static PyObject *
15311unicodeiter_next(unicodeiterobject *it)
15312{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015313 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015314
Benjamin Peterson14339b62009-01-31 16:36:08 +000015315 assert(it != NULL);
15316 seq = it->it_seq;
15317 if (seq == NULL)
15318 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015319 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015321 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15322 int kind = PyUnicode_KIND(seq);
15323 void *data = PyUnicode_DATA(seq);
15324 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15325 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015326 if (item != NULL)
15327 ++it->it_index;
15328 return item;
15329 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015330
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015332 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015334}
15335
15336static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015337unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015338{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 Py_ssize_t len = 0;
15340 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015341 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015342 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015343}
15344
15345PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15346
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015347static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015348unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015349{
15350 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015351 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015352 it->it_seq, it->it_index);
15353 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015354 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015355 if (u == NULL)
15356 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015357 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015358 }
15359}
15360
15361PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15362
15363static PyObject *
15364unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15365{
15366 Py_ssize_t index = PyLong_AsSsize_t(state);
15367 if (index == -1 && PyErr_Occurred())
15368 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015369 if (it->it_seq != NULL) {
15370 if (index < 0)
15371 index = 0;
15372 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15373 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15374 it->it_index = index;
15375 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015376 Py_RETURN_NONE;
15377}
15378
15379PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15380
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015381static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015383 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015384 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15385 reduce_doc},
15386 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15387 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015388 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015389};
15390
15391PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015392 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15393 "str_iterator", /* tp_name */
15394 sizeof(unicodeiterobject), /* tp_basicsize */
15395 0, /* tp_itemsize */
15396 /* methods */
15397 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15398 0, /* tp_print */
15399 0, /* tp_getattr */
15400 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015401 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015402 0, /* tp_repr */
15403 0, /* tp_as_number */
15404 0, /* tp_as_sequence */
15405 0, /* tp_as_mapping */
15406 0, /* tp_hash */
15407 0, /* tp_call */
15408 0, /* tp_str */
15409 PyObject_GenericGetAttr, /* tp_getattro */
15410 0, /* tp_setattro */
15411 0, /* tp_as_buffer */
15412 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15413 0, /* tp_doc */
15414 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15415 0, /* tp_clear */
15416 0, /* tp_richcompare */
15417 0, /* tp_weaklistoffset */
15418 PyObject_SelfIter, /* tp_iter */
15419 (iternextfunc)unicodeiter_next, /* tp_iternext */
15420 unicodeiter_methods, /* tp_methods */
15421 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015422};
15423
15424static PyObject *
15425unicode_iter(PyObject *seq)
15426{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015427 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015428
Benjamin Peterson14339b62009-01-31 16:36:08 +000015429 if (!PyUnicode_Check(seq)) {
15430 PyErr_BadInternalCall();
15431 return NULL;
15432 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015433 if (PyUnicode_READY(seq) == -1)
15434 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015435 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15436 if (it == NULL)
15437 return NULL;
15438 it->it_index = 0;
15439 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015440 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015441 _PyObject_GC_TRACK(it);
15442 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015443}
15444
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015445
15446size_t
15447Py_UNICODE_strlen(const Py_UNICODE *u)
15448{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015449 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015450}
15451
15452Py_UNICODE*
15453Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15454{
15455 Py_UNICODE *u = s1;
15456 while ((*u++ = *s2++));
15457 return s1;
15458}
15459
15460Py_UNICODE*
15461Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15462{
15463 Py_UNICODE *u = s1;
15464 while ((*u++ = *s2++))
15465 if (n-- == 0)
15466 break;
15467 return s1;
15468}
15469
15470Py_UNICODE*
15471Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15472{
15473 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015474 u1 += wcslen(u1);
15475 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015476 return s1;
15477}
15478
15479int
15480Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15481{
15482 while (*s1 && *s2 && *s1 == *s2)
15483 s1++, s2++;
15484 if (*s1 && *s2)
15485 return (*s1 < *s2) ? -1 : +1;
15486 if (*s1)
15487 return 1;
15488 if (*s2)
15489 return -1;
15490 return 0;
15491}
15492
15493int
15494Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15495{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015496 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015497 for (; n != 0; n--) {
15498 u1 = *s1;
15499 u2 = *s2;
15500 if (u1 != u2)
15501 return (u1 < u2) ? -1 : +1;
15502 if (u1 == '\0')
15503 return 0;
15504 s1++;
15505 s2++;
15506 }
15507 return 0;
15508}
15509
15510Py_UNICODE*
15511Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15512{
15513 const Py_UNICODE *p;
15514 for (p = s; *p; p++)
15515 if (*p == c)
15516 return (Py_UNICODE*)p;
15517 return NULL;
15518}
15519
15520Py_UNICODE*
15521Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15522{
15523 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015524 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015525 while (p != s) {
15526 p--;
15527 if (*p == c)
15528 return (Py_UNICODE*)p;
15529 }
15530 return NULL;
15531}
Victor Stinner331ea922010-08-10 16:37:20 +000015532
Victor Stinner71133ff2010-09-01 23:43:53 +000015533Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015534PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015535{
Victor Stinner577db2c2011-10-11 22:12:48 +020015536 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015537 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015538
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015539 if (!PyUnicode_Check(unicode)) {
15540 PyErr_BadArgument();
15541 return NULL;
15542 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015543 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015544 if (u == NULL)
15545 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015546 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015547 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015548 PyErr_NoMemory();
15549 return NULL;
15550 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015551 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015552 size *= sizeof(Py_UNICODE);
15553 copy = PyMem_Malloc(size);
15554 if (copy == NULL) {
15555 PyErr_NoMemory();
15556 return NULL;
15557 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015558 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015559 return copy;
15560}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015561
Georg Brandl66c221e2010-10-14 07:04:07 +000015562/* A _string module, to export formatter_parser and formatter_field_name_split
15563 to the string.Formatter class implemented in Python. */
15564
15565static PyMethodDef _string_methods[] = {
15566 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15567 METH_O, PyDoc_STR("split the argument as a field name")},
15568 {"formatter_parser", (PyCFunction) formatter_parser,
15569 METH_O, PyDoc_STR("parse the argument as a format string")},
15570 {NULL, NULL}
15571};
15572
15573static struct PyModuleDef _string_module = {
15574 PyModuleDef_HEAD_INIT,
15575 "_string",
15576 PyDoc_STR("string helper module"),
15577 0,
15578 _string_methods,
15579 NULL,
15580 NULL,
15581 NULL,
15582 NULL
15583};
15584
15585PyMODINIT_FUNC
15586PyInit__string(void)
15587{
15588 return PyModule_Create(&_string_module);
15589}
15590
15591
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015592#ifdef __cplusplus
15593}
15594#endif