blob: 31703d37ddbd7030c022b13f6cde7191a9bd73e2 [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 Stinner3d4226a2018-08-29 22:21:32 +0200321_Py_error_handler
322_Py_GetErrorHandler(const char *errors)
Victor Stinner50149202015-09-22 00:26:54 +0200323{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200324 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200325 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200326 }
327 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200328 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200329 }
330 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200331 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200332 }
333 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200334 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200335 }
336 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200337 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200338 }
339 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200340 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200341 }
342 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200343 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200344 }
Victor Stinner50149202015-09-22 00:26:54 +0200345 return _Py_ERROR_OTHER;
346}
347
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300348/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
349 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000350Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000351PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000352{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000353#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000354 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000355#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000356 /* This is actually an illegal character, so it should
357 not be passed to unichr. */
358 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000359#endif
360}
361
Victor Stinner910337b2011-10-03 03:20:16 +0200362#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200363int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100364_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200365{
366 PyASCIIObject *ascii;
367 unsigned int kind;
368
369 assert(PyUnicode_Check(op));
370
371 ascii = (PyASCIIObject *)op;
372 kind = ascii->state.kind;
373
Victor Stinnera3b334d2011-10-03 13:53:37 +0200374 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200375 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200376 assert(ascii->state.ready == 1);
377 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200378 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200379 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200380 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200381
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 if (ascii->state.compact == 1) {
383 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200384 assert(kind == PyUnicode_1BYTE_KIND
385 || kind == PyUnicode_2BYTE_KIND
386 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200387 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200389 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100390 }
391 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200392 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
393
394 data = unicode->data.any;
395 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100396 assert(ascii->length == 0);
397 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200398 assert(ascii->state.compact == 0);
399 assert(ascii->state.ascii == 0);
400 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100401 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200402 assert(ascii->wstr != NULL);
403 assert(data == NULL);
404 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200405 }
406 else {
407 assert(kind == PyUnicode_1BYTE_KIND
408 || kind == PyUnicode_2BYTE_KIND
409 || kind == PyUnicode_4BYTE_KIND);
410 assert(ascii->state.compact == 0);
411 assert(ascii->state.ready == 1);
412 assert(data != NULL);
413 if (ascii->state.ascii) {
414 assert (compact->utf8 == data);
415 assert (compact->utf8_length == ascii->length);
416 }
417 else
418 assert (compact->utf8 != data);
419 }
420 }
421 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200422 if (
423#if SIZEOF_WCHAR_T == 2
424 kind == PyUnicode_2BYTE_KIND
425#else
426 kind == PyUnicode_4BYTE_KIND
427#endif
428 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200429 {
430 assert(ascii->wstr == data);
431 assert(compact->wstr_length == ascii->length);
432 } else
433 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200434 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200435
436 if (compact->utf8 == NULL)
437 assert(compact->utf8_length == 0);
438 if (ascii->wstr == NULL)
439 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200440 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200441 /* check that the best kind is used */
442 if (check_content && kind != PyUnicode_WCHAR_KIND)
443 {
444 Py_ssize_t i;
445 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200446 void *data;
447 Py_UCS4 ch;
448
449 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200450 for (i=0; i < ascii->length; i++)
451 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200452 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 if (ch > maxchar)
454 maxchar = ch;
455 }
456 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100457 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200458 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100459 assert(maxchar <= 255);
460 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200461 else
462 assert(maxchar < 128);
463 }
Victor Stinner77faf692011-11-20 18:56:05 +0100464 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200465 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100466 assert(maxchar <= 0xFFFF);
467 }
468 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200469 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100470 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100471 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200472 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200473 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400474 return 1;
475}
Victor Stinner910337b2011-10-03 03:20:16 +0200476#endif
477
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100478static PyObject*
479unicode_result_wchar(PyObject *unicode)
480{
481#ifndef Py_DEBUG
482 Py_ssize_t len;
483
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100484 len = _PyUnicode_WSTR_LENGTH(unicode);
485 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100486 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200487 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100488 }
489
490 if (len == 1) {
491 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100492 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100493 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
494 Py_DECREF(unicode);
495 return latin1_char;
496 }
497 }
498
499 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200500 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100501 return NULL;
502 }
503#else
Victor Stinneraa771272012-10-04 02:32:58 +0200504 assert(Py_REFCNT(unicode) == 1);
505
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100506 /* don't make the result ready in debug mode to ensure that the caller
507 makes the string ready before using it */
508 assert(_PyUnicode_CheckConsistency(unicode, 1));
509#endif
510 return unicode;
511}
512
513static PyObject*
514unicode_result_ready(PyObject *unicode)
515{
516 Py_ssize_t length;
517
518 length = PyUnicode_GET_LENGTH(unicode);
519 if (length == 0) {
520 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100521 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200522 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100523 }
524 return unicode_empty;
525 }
526
527 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200528 void *data = PyUnicode_DATA(unicode);
529 int kind = PyUnicode_KIND(unicode);
530 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100531 if (ch < 256) {
532 PyObject *latin1_char = unicode_latin1[ch];
533 if (latin1_char != NULL) {
534 if (unicode != latin1_char) {
535 Py_INCREF(latin1_char);
536 Py_DECREF(unicode);
537 }
538 return latin1_char;
539 }
540 else {
541 assert(_PyUnicode_CheckConsistency(unicode, 1));
542 Py_INCREF(unicode);
543 unicode_latin1[ch] = unicode;
544 return unicode;
545 }
546 }
547 }
548
549 assert(_PyUnicode_CheckConsistency(unicode, 1));
550 return unicode;
551}
552
553static PyObject*
554unicode_result(PyObject *unicode)
555{
556 assert(_PyUnicode_CHECK(unicode));
557 if (PyUnicode_IS_READY(unicode))
558 return unicode_result_ready(unicode);
559 else
560 return unicode_result_wchar(unicode);
561}
562
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563static PyObject*
564unicode_result_unchanged(PyObject *unicode)
565{
566 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500567 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100568 return NULL;
569 Py_INCREF(unicode);
570 return unicode;
571 }
572 else
573 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100574 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100575}
576
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200577/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
578 ASCII, Latin1, UTF-8, etc. */
579static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200580backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200581 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
582{
Victor Stinnerad771582015-10-09 12:38:53 +0200583 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200584 Py_UCS4 ch;
585 enum PyUnicode_Kind kind;
586 void *data;
587
588 assert(PyUnicode_IS_READY(unicode));
589 kind = PyUnicode_KIND(unicode);
590 data = PyUnicode_DATA(unicode);
591
592 size = 0;
593 /* determine replacement size */
594 for (i = collstart; i < collend; ++i) {
595 Py_ssize_t incr;
596
597 ch = PyUnicode_READ(kind, data, i);
598 if (ch < 0x100)
599 incr = 2+2;
600 else if (ch < 0x10000)
601 incr = 2+4;
602 else {
603 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200604 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200605 }
606 if (size > PY_SSIZE_T_MAX - incr) {
607 PyErr_SetString(PyExc_OverflowError,
608 "encoded result is too long for a Python string");
609 return NULL;
610 }
611 size += incr;
612 }
613
Victor Stinnerad771582015-10-09 12:38:53 +0200614 str = _PyBytesWriter_Prepare(writer, str, size);
615 if (str == NULL)
616 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200617
618 /* generate replacement */
619 for (i = collstart; i < collend; ++i) {
620 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200621 *str++ = '\\';
622 if (ch >= 0x00010000) {
623 *str++ = 'U';
624 *str++ = Py_hexdigits[(ch>>28)&0xf];
625 *str++ = Py_hexdigits[(ch>>24)&0xf];
626 *str++ = Py_hexdigits[(ch>>20)&0xf];
627 *str++ = Py_hexdigits[(ch>>16)&0xf];
628 *str++ = Py_hexdigits[(ch>>12)&0xf];
629 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200630 }
Victor Stinner797485e2015-10-09 03:17:30 +0200631 else if (ch >= 0x100) {
632 *str++ = 'u';
633 *str++ = Py_hexdigits[(ch>>12)&0xf];
634 *str++ = Py_hexdigits[(ch>>8)&0xf];
635 }
636 else
637 *str++ = 'x';
638 *str++ = Py_hexdigits[(ch>>4)&0xf];
639 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200640 }
641 return str;
642}
643
644/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
645 ASCII, Latin1, UTF-8, etc. */
646static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200647xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200648 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
649{
Victor Stinnerad771582015-10-09 12:38:53 +0200650 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200651 Py_UCS4 ch;
652 enum PyUnicode_Kind kind;
653 void *data;
654
655 assert(PyUnicode_IS_READY(unicode));
656 kind = PyUnicode_KIND(unicode);
657 data = PyUnicode_DATA(unicode);
658
659 size = 0;
660 /* determine replacement size */
661 for (i = collstart; i < collend; ++i) {
662 Py_ssize_t incr;
663
664 ch = PyUnicode_READ(kind, data, i);
665 if (ch < 10)
666 incr = 2+1+1;
667 else if (ch < 100)
668 incr = 2+2+1;
669 else if (ch < 1000)
670 incr = 2+3+1;
671 else if (ch < 10000)
672 incr = 2+4+1;
673 else if (ch < 100000)
674 incr = 2+5+1;
675 else if (ch < 1000000)
676 incr = 2+6+1;
677 else {
678 assert(ch <= MAX_UNICODE);
679 incr = 2+7+1;
680 }
681 if (size > PY_SSIZE_T_MAX - incr) {
682 PyErr_SetString(PyExc_OverflowError,
683 "encoded result is too long for a Python string");
684 return NULL;
685 }
686 size += incr;
687 }
688
Victor Stinnerad771582015-10-09 12:38:53 +0200689 str = _PyBytesWriter_Prepare(writer, str, size);
690 if (str == NULL)
691 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200692
693 /* generate replacement */
694 for (i = collstart; i < collend; ++i) {
695 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
696 }
697 return str;
698}
699
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700/* --- Bloom Filters ----------------------------------------------------- */
701
702/* stuff to implement simple "bloom filters" for Unicode characters.
703 to keep things simple, we use a single bitmask, using the least 5
704 bits from each unicode characters as the bit index. */
705
706/* the linebreak mask is set up by Unicode_Init below */
707
Antoine Pitrouf068f942010-01-13 14:19:12 +0000708#if LONG_BIT >= 128
709#define BLOOM_WIDTH 128
710#elif LONG_BIT >= 64
711#define BLOOM_WIDTH 64
712#elif LONG_BIT >= 32
713#define BLOOM_WIDTH 32
714#else
715#error "LONG_BIT is smaller than 32"
716#endif
717
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718#define BLOOM_MASK unsigned long
719
Serhiy Storchaka05997252013-01-26 12:14:02 +0200720static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000721
Antoine Pitrouf068f942010-01-13 14:19:12 +0000722#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723
Benjamin Peterson29060642009-01-31 22:14:21 +0000724#define BLOOM_LINEBREAK(ch) \
725 ((ch) < 128U ? ascii_linebreak[(ch)] : \
726 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000727
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700728static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730{
Victor Stinnera85af502013-04-09 21:53:54 +0200731#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
732 do { \
733 TYPE *data = (TYPE *)PTR; \
734 TYPE *end = data + LEN; \
735 Py_UCS4 ch; \
736 for (; data != end; data++) { \
737 ch = *data; \
738 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
739 } \
740 break; \
741 } while (0)
742
Thomas Wouters477c8d52006-05-27 19:21:47 +0000743 /* calculate simple bloom-style bitmask for a given unicode string */
744
Antoine Pitrouf068f942010-01-13 14:19:12 +0000745 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000746
747 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200748 switch (kind) {
749 case PyUnicode_1BYTE_KIND:
750 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
751 break;
752 case PyUnicode_2BYTE_KIND:
753 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
754 break;
755 case PyUnicode_4BYTE_KIND:
756 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
757 break;
758 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700759 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200760 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200762
763#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000764}
765
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300766static int
767ensure_unicode(PyObject *obj)
768{
769 if (!PyUnicode_Check(obj)) {
770 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +0200771 "must be str, not %.100s",
772 Py_TYPE(obj)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300773 return -1;
774 }
775 return PyUnicode_READY(obj);
776}
777
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200778/* Compilation of templated routines */
779
780#include "stringlib/asciilib.h"
781#include "stringlib/fastsearch.h"
782#include "stringlib/partition.h"
783#include "stringlib/split.h"
784#include "stringlib/count.h"
785#include "stringlib/find.h"
786#include "stringlib/find_max_char.h"
787#include "stringlib/localeutil.h"
788#include "stringlib/undef.h"
789
790#include "stringlib/ucs1lib.h"
791#include "stringlib/fastsearch.h"
792#include "stringlib/partition.h"
793#include "stringlib/split.h"
794#include "stringlib/count.h"
795#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300796#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200797#include "stringlib/find_max_char.h"
798#include "stringlib/localeutil.h"
799#include "stringlib/undef.h"
800
801#include "stringlib/ucs2lib.h"
802#include "stringlib/fastsearch.h"
803#include "stringlib/partition.h"
804#include "stringlib/split.h"
805#include "stringlib/count.h"
806#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300807#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200808#include "stringlib/find_max_char.h"
809#include "stringlib/localeutil.h"
810#include "stringlib/undef.h"
811
812#include "stringlib/ucs4lib.h"
813#include "stringlib/fastsearch.h"
814#include "stringlib/partition.h"
815#include "stringlib/split.h"
816#include "stringlib/count.h"
817#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300818#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200819#include "stringlib/find_max_char.h"
820#include "stringlib/localeutil.h"
821#include "stringlib/undef.h"
822
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823#include "stringlib/unicodedefs.h"
824#include "stringlib/fastsearch.h"
825#include "stringlib/count.h"
826#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100827#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200828
Guido van Rossumd57fd912000-03-10 22:53:23 +0000829/* --- Unicode Object ----------------------------------------------------- */
830
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700831static inline Py_ssize_t
832findchar(const void *s, int kind,
833 Py_ssize_t size, Py_UCS4 ch,
834 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200835{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200836 switch (kind) {
837 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200838 if ((Py_UCS1) ch != ch)
839 return -1;
840 if (direction > 0)
841 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
842 else
843 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200844 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200845 if ((Py_UCS2) ch != ch)
846 return -1;
847 if (direction > 0)
848 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
849 else
850 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200851 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200852 if (direction > 0)
853 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
854 else
855 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200856 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700857 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200859}
860
Victor Stinnerafffce42012-10-03 23:03:17 +0200861#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000862/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200863 earlier.
864
865 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
866 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
867 invalid character in Unicode 6.0. */
868static void
869unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
870{
871 int kind = PyUnicode_KIND(unicode);
872 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
873 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
874 if (length <= old_length)
875 return;
876 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
877}
878#endif
879
Victor Stinnerfe226c02011-10-03 03:52:20 +0200880static PyObject*
881resize_compact(PyObject *unicode, Py_ssize_t length)
882{
883 Py_ssize_t char_size;
884 Py_ssize_t struct_size;
885 Py_ssize_t new_size;
886 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100887 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200888#ifdef Py_DEBUG
889 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
890#endif
891
Victor Stinner79891572012-05-03 13:43:07 +0200892 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200893 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100894 assert(PyUnicode_IS_COMPACT(unicode));
895
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200896 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100897 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200898 struct_size = sizeof(PyASCIIObject);
899 else
900 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200901 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200902
Victor Stinnerfe226c02011-10-03 03:52:20 +0200903 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
904 PyErr_NoMemory();
905 return NULL;
906 }
907 new_size = (struct_size + (length + 1) * char_size);
908
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200909 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
910 PyObject_DEL(_PyUnicode_UTF8(unicode));
911 _PyUnicode_UTF8(unicode) = NULL;
912 _PyUnicode_UTF8_LENGTH(unicode) = 0;
913 }
Victor Stinner84def372011-12-11 20:04:56 +0100914 _Py_DEC_REFTOTAL;
915 _Py_ForgetReference(unicode);
916
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300917 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100918 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100919 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200920 PyErr_NoMemory();
921 return NULL;
922 }
Victor Stinner84def372011-12-11 20:04:56 +0100923 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200924 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100925
Victor Stinnerfe226c02011-10-03 03:52:20 +0200926 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200927 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200928 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100929 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200930 _PyUnicode_WSTR_LENGTH(unicode) = length;
931 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100932 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
933 PyObject_DEL(_PyUnicode_WSTR(unicode));
934 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100935 if (!PyUnicode_IS_ASCII(unicode))
936 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100937 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200938#ifdef Py_DEBUG
939 unicode_fill_invalid(unicode, old_length);
940#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200941 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
942 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200943 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200944 return unicode;
945}
946
Alexander Belopolsky40018472011-02-26 01:02:56 +0000947static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200948resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000949{
Victor Stinner95663112011-10-04 01:03:50 +0200950 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100951 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200952 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000954
Victor Stinnerfe226c02011-10-03 03:52:20 +0200955 if (PyUnicode_IS_READY(unicode)) {
956 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200957 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200958 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200959#ifdef Py_DEBUG
960 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
961#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200962
963 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200964 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200965 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
966 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967
968 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
969 PyErr_NoMemory();
970 return -1;
971 }
972 new_size = (length + 1) * char_size;
973
Victor Stinner7a9105a2011-12-12 00:13:42 +0100974 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
975 {
976 PyObject_DEL(_PyUnicode_UTF8(unicode));
977 _PyUnicode_UTF8(unicode) = NULL;
978 _PyUnicode_UTF8_LENGTH(unicode) = 0;
979 }
980
Victor Stinnerfe226c02011-10-03 03:52:20 +0200981 data = (PyObject *)PyObject_REALLOC(data, new_size);
982 if (data == NULL) {
983 PyErr_NoMemory();
984 return -1;
985 }
986 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200987 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200988 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200989 _PyUnicode_WSTR_LENGTH(unicode) = length;
990 }
991 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200992 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200993 _PyUnicode_UTF8_LENGTH(unicode) = length;
994 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200995 _PyUnicode_LENGTH(unicode) = length;
996 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200997#ifdef Py_DEBUG
998 unicode_fill_invalid(unicode, old_length);
999#endif
Victor Stinner95663112011-10-04 01:03:50 +02001000 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001001 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001004 }
Victor Stinner95663112011-10-04 01:03:50 +02001005 assert(_PyUnicode_WSTR(unicode) != NULL);
1006
1007 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001008 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001009 PyErr_NoMemory();
1010 return -1;
1011 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001012 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001013 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001014 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001015 if (!wstr) {
1016 PyErr_NoMemory();
1017 return -1;
1018 }
1019 _PyUnicode_WSTR(unicode) = wstr;
1020 _PyUnicode_WSTR(unicode)[length] = 0;
1021 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001022 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001023 return 0;
1024}
1025
Victor Stinnerfe226c02011-10-03 03:52:20 +02001026static PyObject*
1027resize_copy(PyObject *unicode, Py_ssize_t length)
1028{
1029 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001030 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001031 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001032
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001033 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001034
1035 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1036 if (copy == NULL)
1037 return NULL;
1038
1039 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001040 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001041 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001042 }
1043 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001044 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001045
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001046 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001047 if (w == NULL)
1048 return NULL;
1049 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1050 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001051 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001052 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001053 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001054 }
1055}
1056
Guido van Rossumd57fd912000-03-10 22:53:23 +00001057/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001058 Ux0000 terminated; some code (e.g. new_identifier)
1059 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001060
1061 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001062 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001063
1064*/
1065
Alexander Belopolsky40018472011-02-26 01:02:56 +00001066static PyUnicodeObject *
1067_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001068{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001069 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001071
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001073 if (length == 0 && unicode_empty != NULL) {
1074 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001075 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001076 }
1077
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001078 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001079 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001080 return (PyUnicodeObject *)PyErr_NoMemory();
1081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 if (length < 0) {
1083 PyErr_SetString(PyExc_SystemError,
1084 "Negative size passed to _PyUnicode_New");
1085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001086 }
1087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001088 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1089 if (unicode == NULL)
1090 return NULL;
1091 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001092
1093 _PyUnicode_WSTR_LENGTH(unicode) = length;
1094 _PyUnicode_HASH(unicode) = -1;
1095 _PyUnicode_STATE(unicode).interned = 0;
1096 _PyUnicode_STATE(unicode).kind = 0;
1097 _PyUnicode_STATE(unicode).compact = 0;
1098 _PyUnicode_STATE(unicode).ready = 0;
1099 _PyUnicode_STATE(unicode).ascii = 0;
1100 _PyUnicode_DATA_ANY(unicode) = NULL;
1101 _PyUnicode_LENGTH(unicode) = 0;
1102 _PyUnicode_UTF8(unicode) = NULL;
1103 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1106 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001107 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001108 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001109 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111
Jeremy Hyltond8082792003-09-16 19:41:39 +00001112 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001113 * the caller fails before initializing str -- unicode_resize()
1114 * reads str[0], and the Keep-Alive optimization can keep memory
1115 * allocated for str alive across a call to unicode_dealloc(unicode).
1116 * We don't want unicode_resize to read uninitialized memory in
1117 * that case.
1118 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 _PyUnicode_WSTR(unicode)[0] = 0;
1120 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001121
Victor Stinner7931d9a2011-11-04 00:22:48 +01001122 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001123 return unicode;
1124}
1125
Victor Stinnerf42dc442011-10-02 23:33:16 +02001126static const char*
1127unicode_kind_name(PyObject *unicode)
1128{
Victor Stinner42dfd712011-10-03 14:41:45 +02001129 /* don't check consistency: unicode_kind_name() is called from
1130 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001131 if (!PyUnicode_IS_COMPACT(unicode))
1132 {
1133 if (!PyUnicode_IS_READY(unicode))
1134 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001135 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001136 {
1137 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 return "legacy ascii";
1140 else
1141 return "legacy latin1";
1142 case PyUnicode_2BYTE_KIND:
1143 return "legacy UCS2";
1144 case PyUnicode_4BYTE_KIND:
1145 return "legacy UCS4";
1146 default:
1147 return "<legacy invalid kind>";
1148 }
1149 }
1150 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001151 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001153 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001154 return "ascii";
1155 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001156 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001157 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001158 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001159 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001160 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001161 default:
1162 return "<invalid compact kind>";
1163 }
1164}
1165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167/* Functions wrapping macros for use in debugger */
1168char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001169 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170}
1171
1172void *_PyUnicode_compact_data(void *unicode) {
1173 return _PyUnicode_COMPACT_DATA(unicode);
1174}
1175void *_PyUnicode_data(void *unicode){
1176 printf("obj %p\n", unicode);
1177 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1178 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1179 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1180 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1181 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1182 return PyUnicode_DATA(unicode);
1183}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001184
1185void
1186_PyUnicode_Dump(PyObject *op)
1187{
1188 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001189 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1190 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1191 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001192
Victor Stinnera849a4b2011-10-03 12:12:11 +02001193 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001194 {
1195 if (ascii->state.ascii)
1196 data = (ascii + 1);
1197 else
1198 data = (compact + 1);
1199 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001200 else
1201 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001202 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1203 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->wstr == data)
1206 printf("shared ");
1207 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001208
Victor Stinnera3b334d2011-10-03 13:53:37 +02001209 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001210 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001211 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1212 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001213 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1214 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001215 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001216 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001217}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218#endif
1219
1220PyObject *
1221PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1222{
1223 PyObject *obj;
1224 PyCompactUnicodeObject *unicode;
1225 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001226 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001227 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 Py_ssize_t char_size;
1229 Py_ssize_t struct_size;
1230
1231 /* Optimization for empty strings */
1232 if (size == 0 && unicode_empty != NULL) {
1233 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001234 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235 }
1236
Victor Stinner9e9d6892011-10-04 01:02:02 +02001237 is_ascii = 0;
1238 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001239 struct_size = sizeof(PyCompactUnicodeObject);
1240 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001241 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001242 char_size = 1;
1243 is_ascii = 1;
1244 struct_size = sizeof(PyASCIIObject);
1245 }
1246 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001247 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248 char_size = 1;
1249 }
1250 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001251 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 char_size = 2;
1253 if (sizeof(wchar_t) == 2)
1254 is_sharing = 1;
1255 }
1256 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001257 if (maxchar > MAX_UNICODE) {
1258 PyErr_SetString(PyExc_SystemError,
1259 "invalid maximum character passed to PyUnicode_New");
1260 return NULL;
1261 }
Victor Stinner8f825062012-04-27 13:55:39 +02001262 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 char_size = 4;
1264 if (sizeof(wchar_t) == 4)
1265 is_sharing = 1;
1266 }
1267
1268 /* Ensure we won't overflow the size. */
1269 if (size < 0) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "Negative size passed to PyUnicode_New");
1272 return NULL;
1273 }
1274 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1275 return PyErr_NoMemory();
1276
1277 /* Duplicated allocation code from _PyObject_New() instead of a call to
1278 * PyObject_New() so we are able to allocate space for the object and
1279 * it's data buffer.
1280 */
1281 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1282 if (obj == NULL)
1283 return PyErr_NoMemory();
1284 obj = PyObject_INIT(obj, &PyUnicode_Type);
1285 if (obj == NULL)
1286 return NULL;
1287
1288 unicode = (PyCompactUnicodeObject *)obj;
1289 if (is_ascii)
1290 data = ((PyASCIIObject*)obj) + 1;
1291 else
1292 data = unicode + 1;
1293 _PyUnicode_LENGTH(unicode) = size;
1294 _PyUnicode_HASH(unicode) = -1;
1295 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001296 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 _PyUnicode_STATE(unicode).compact = 1;
1298 _PyUnicode_STATE(unicode).ready = 1;
1299 _PyUnicode_STATE(unicode).ascii = is_ascii;
1300 if (is_ascii) {
1301 ((char*)data)[size] = 0;
1302 _PyUnicode_WSTR(unicode) = NULL;
1303 }
Victor Stinner8f825062012-04-27 13:55:39 +02001304 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 ((char*)data)[size] = 0;
1306 _PyUnicode_WSTR(unicode) = NULL;
1307 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001309 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 else {
1312 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001313 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001314 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((Py_UCS4*)data)[size] = 0;
1318 if (is_sharing) {
1319 _PyUnicode_WSTR_LENGTH(unicode) = size;
1320 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1321 }
1322 else {
1323 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1324 _PyUnicode_WSTR(unicode) = NULL;
1325 }
1326 }
Victor Stinner8f825062012-04-27 13:55:39 +02001327#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001328 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001329#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001330 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001331 return obj;
1332}
1333
1334#if SIZEOF_WCHAR_T == 2
1335/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1336 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001337 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338
1339 This function assumes that unicode can hold one more code point than wstr
1340 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001341static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001343 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344{
1345 const wchar_t *iter;
1346 Py_UCS4 *ucs4_out;
1347
Victor Stinner910337b2011-10-03 03:20:16 +02001348 assert(unicode != NULL);
1349 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1351 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1352
1353 for (iter = begin; iter < end; ) {
1354 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1355 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001356 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1357 && (iter+1) < end
1358 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001359 {
Victor Stinner551ac952011-11-29 22:58:13 +01001360 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 iter += 2;
1362 }
1363 else {
1364 *ucs4_out++ = *iter;
1365 iter++;
1366 }
1367 }
1368 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1369 _PyUnicode_GET_LENGTH(unicode)));
1370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371}
1372#endif
1373
Victor Stinnercd9950f2011-10-02 00:34:53 +02001374static int
Victor Stinner488fa492011-12-12 00:01:39 +01001375unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001376{
Victor Stinner488fa492011-12-12 00:01:39 +01001377 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001378 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001379 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001380 return -1;
1381 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001382 return 0;
1383}
1384
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385static int
1386_copy_characters(PyObject *to, Py_ssize_t to_start,
1387 PyObject *from, Py_ssize_t from_start,
1388 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001390 unsigned int from_kind, to_kind;
1391 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
Victor Stinneree4544c2012-05-09 22:24:08 +02001393 assert(0 <= how_many);
1394 assert(0 <= from_start);
1395 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001398 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399
Victor Stinnerd3f08822012-05-29 12:57:52 +02001400 assert(PyUnicode_Check(to));
1401 assert(PyUnicode_IS_READY(to));
1402 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1403
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001404 if (how_many == 0)
1405 return 0;
1406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001408 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001410 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerf1852262012-06-16 16:38:26 +02001412#ifdef Py_DEBUG
1413 if (!check_maxchar
1414 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1415 {
1416 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1417 Py_UCS4 ch;
1418 Py_ssize_t i;
1419 for (i=0; i < how_many; i++) {
1420 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1421 assert(ch <= to_maxchar);
1422 }
1423 }
1424#endif
1425
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001426 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001427 if (check_maxchar
1428 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1429 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001430 /* Writing Latin-1 characters into an ASCII string requires to
1431 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001432 Py_UCS4 max_char;
1433 max_char = ucs1lib_find_max_char(from_data,
1434 (Py_UCS1*)from_data + how_many);
1435 if (max_char >= 128)
1436 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001437 }
Christian Heimesf051e432016-09-13 20:22:02 +02001438 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001439 (char*)from_data + from_kind * from_start,
1440 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001441 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001442 else if (from_kind == PyUnicode_1BYTE_KIND
1443 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001444 {
1445 _PyUnicode_CONVERT_BYTES(
1446 Py_UCS1, Py_UCS2,
1447 PyUnicode_1BYTE_DATA(from) + from_start,
1448 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1449 PyUnicode_2BYTE_DATA(to) + to_start
1450 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001451 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001452 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001453 && to_kind == PyUnicode_4BYTE_KIND)
1454 {
1455 _PyUnicode_CONVERT_BYTES(
1456 Py_UCS1, Py_UCS4,
1457 PyUnicode_1BYTE_DATA(from) + from_start,
1458 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1459 PyUnicode_4BYTE_DATA(to) + to_start
1460 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001461 }
1462 else if (from_kind == PyUnicode_2BYTE_KIND
1463 && to_kind == PyUnicode_4BYTE_KIND)
1464 {
1465 _PyUnicode_CONVERT_BYTES(
1466 Py_UCS2, Py_UCS4,
1467 PyUnicode_2BYTE_DATA(from) + from_start,
1468 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1469 PyUnicode_4BYTE_DATA(to) + to_start
1470 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001471 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001472 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001473 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1474
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001475 if (!check_maxchar) {
1476 if (from_kind == PyUnicode_2BYTE_KIND
1477 && to_kind == PyUnicode_1BYTE_KIND)
1478 {
1479 _PyUnicode_CONVERT_BYTES(
1480 Py_UCS2, Py_UCS1,
1481 PyUnicode_2BYTE_DATA(from) + from_start,
1482 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1483 PyUnicode_1BYTE_DATA(to) + to_start
1484 );
1485 }
1486 else if (from_kind == PyUnicode_4BYTE_KIND
1487 && to_kind == PyUnicode_1BYTE_KIND)
1488 {
1489 _PyUnicode_CONVERT_BYTES(
1490 Py_UCS4, Py_UCS1,
1491 PyUnicode_4BYTE_DATA(from) + from_start,
1492 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1493 PyUnicode_1BYTE_DATA(to) + to_start
1494 );
1495 }
1496 else if (from_kind == PyUnicode_4BYTE_KIND
1497 && to_kind == PyUnicode_2BYTE_KIND)
1498 {
1499 _PyUnicode_CONVERT_BYTES(
1500 Py_UCS4, Py_UCS2,
1501 PyUnicode_4BYTE_DATA(from) + from_start,
1502 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1503 PyUnicode_2BYTE_DATA(to) + to_start
1504 );
1505 }
1506 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001507 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001508 }
1509 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001510 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001511 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 Py_ssize_t i;
1514
Victor Stinnera0702ab2011-09-29 14:14:38 +02001515 for (i=0; i < how_many; i++) {
1516 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001517 if (ch > to_maxchar)
1518 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001519 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1520 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001521 }
1522 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523 return 0;
1524}
1525
Victor Stinnerd3f08822012-05-29 12:57:52 +02001526void
1527_PyUnicode_FastCopyCharacters(
1528 PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530{
1531 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1532}
1533
1534Py_ssize_t
1535PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1536 PyObject *from, Py_ssize_t from_start,
1537 Py_ssize_t how_many)
1538{
1539 int err;
1540
1541 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545
Benjamin Petersonbac79492012-01-14 13:34:47 -05001546 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001548 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 return -1;
1550
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001551 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 PyErr_SetString(PyExc_IndexError, "string index out of range");
1553 return -1;
1554 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001555 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001556 PyErr_SetString(PyExc_IndexError, "string index out of range");
1557 return -1;
1558 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001559 if (how_many < 0) {
1560 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1561 return -1;
1562 }
1563 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1565 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001566 "Cannot write %zi characters at %zi "
1567 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001568 how_many, to_start, PyUnicode_GET_LENGTH(to));
1569 return -1;
1570 }
1571
1572 if (how_many == 0)
1573 return 0;
1574
Victor Stinner488fa492011-12-12 00:01:39 +01001575 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 return -1;
1577
1578 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1579 if (err) {
1580 PyErr_Format(PyExc_SystemError,
1581 "Cannot copy %s characters "
1582 "into a string of %s characters",
1583 unicode_kind_name(from),
1584 unicode_kind_name(to));
1585 return -1;
1586 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001587 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588}
1589
Victor Stinner17222162011-09-28 22:15:37 +02001590/* Find the maximum code point and count the number of surrogate pairs so a
1591 correct string length can be computed before converting a string to UCS4.
1592 This function counts single surrogates as a character and not as a pair.
1593
1594 Return 0 on success, or -1 on error. */
1595static int
1596find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1597 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598{
1599 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001600 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601
Victor Stinnerc53be962011-10-02 21:33:54 +02001602 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 *num_surrogates = 0;
1604 *maxchar = 0;
1605
1606 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001608 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1609 && (iter+1) < end
1610 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1611 {
1612 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1613 ++(*num_surrogates);
1614 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 }
1616 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001618 {
1619 ch = *iter;
1620 iter++;
1621 }
1622 if (ch > *maxchar) {
1623 *maxchar = ch;
1624 if (*maxchar > MAX_UNICODE) {
1625 PyErr_Format(PyExc_ValueError,
1626 "character U+%x is not in range [U+0000; U+10ffff]",
1627 ch);
1628 return -1;
1629 }
1630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631 }
1632 return 0;
1633}
1634
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001635int
1636_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637{
1638 wchar_t *end;
1639 Py_UCS4 maxchar = 0;
1640 Py_ssize_t num_surrogates;
1641#if SIZEOF_WCHAR_T == 2
1642 Py_ssize_t length_wo_surrogates;
1643#endif
1644
Georg Brandl7597add2011-10-05 16:36:47 +02001645 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001646 strings were created using _PyObject_New() and where no canonical
1647 representation (the str field) has been set yet aka strings
1648 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001649 assert(_PyUnicode_CHECK(unicode));
1650 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001652 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001653 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001654 /* Actually, it should neither be interned nor be anything else: */
1655 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001658 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001659 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661
1662 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001663 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1664 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 PyErr_NoMemory();
1666 return -1;
1667 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001668 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 _PyUnicode_WSTR(unicode), end,
1670 PyUnicode_1BYTE_DATA(unicode));
1671 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1672 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1673 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1674 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001675 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001676 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001678 }
1679 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001680 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001681 _PyUnicode_UTF8(unicode) = NULL;
1682 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001683 }
1684 PyObject_FREE(_PyUnicode_WSTR(unicode));
1685 _PyUnicode_WSTR(unicode) = NULL;
1686 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1687 }
1688 /* In this case we might have to convert down from 4-byte native
1689 wchar_t to 2-byte unicode. */
1690 else if (maxchar < 65536) {
1691 assert(num_surrogates == 0 &&
1692 "FindMaxCharAndNumSurrogatePairs() messed up");
1693
Victor Stinner506f5922011-09-28 22:34:18 +02001694#if SIZEOF_WCHAR_T == 2
1695 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001696 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001697 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1698 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1699 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001700 _PyUnicode_UTF8(unicode) = NULL;
1701 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001702#else
1703 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001704 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001705 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001706 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001707 PyErr_NoMemory();
1708 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 }
Victor Stinner506f5922011-09-28 22:34:18 +02001710 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1711 _PyUnicode_WSTR(unicode), end,
1712 PyUnicode_2BYTE_DATA(unicode));
1713 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1714 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1715 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001716 _PyUnicode_UTF8(unicode) = NULL;
1717 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001718 PyObject_FREE(_PyUnicode_WSTR(unicode));
1719 _PyUnicode_WSTR(unicode) = NULL;
1720 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1721#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 }
1723 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1724 else {
1725#if SIZEOF_WCHAR_T == 2
1726 /* in case the native representation is 2-bytes, we need to allocate a
1727 new normalized 4-byte version. */
1728 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001729 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1730 PyErr_NoMemory();
1731 return -1;
1732 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001733 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1734 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 PyErr_NoMemory();
1736 return -1;
1737 }
1738 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1739 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001740 _PyUnicode_UTF8(unicode) = NULL;
1741 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001742 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1743 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001744 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 PyObject_FREE(_PyUnicode_WSTR(unicode));
1746 _PyUnicode_WSTR(unicode) = NULL;
1747 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1748#else
1749 assert(num_surrogates == 0);
1750
Victor Stinnerc3c74152011-10-02 20:39:55 +02001751 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001753 _PyUnicode_UTF8(unicode) = NULL;
1754 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1756#endif
1757 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1758 }
1759 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001760 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 return 0;
1762}
1763
Alexander Belopolsky40018472011-02-26 01:02:56 +00001764static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001765unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766{
Walter Dörwald16807132007-05-25 13:52:07 +00001767 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_NOT_INTERNED:
1769 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001770
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 case SSTATE_INTERNED_MORTAL:
1772 /* revive dead object temporarily for DelItem */
1773 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001774 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 Py_FatalError(
1776 "deletion of interned string failed");
1777 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001778
Benjamin Peterson29060642009-01-31 22:14:21 +00001779 case SSTATE_INTERNED_IMMORTAL:
1780 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001781 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 default:
1784 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001785 }
1786
Victor Stinner03490912011-10-03 23:45:12 +02001787 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001789 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001790 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001791 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1792 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001794 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001795}
1796
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001797#ifdef Py_DEBUG
1798static int
1799unicode_is_singleton(PyObject *unicode)
1800{
1801 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1802 if (unicode == unicode_empty)
1803 return 1;
1804 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1805 {
1806 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1807 if (ch < 256 && unicode_latin1[ch] == unicode)
1808 return 1;
1809 }
1810 return 0;
1811}
1812#endif
1813
Alexander Belopolsky40018472011-02-26 01:02:56 +00001814static int
Victor Stinner488fa492011-12-12 00:01:39 +01001815unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001816{
Victor Stinner488fa492011-12-12 00:01:39 +01001817 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001818 if (Py_REFCNT(unicode) != 1)
1819 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001820 if (_PyUnicode_HASH(unicode) != -1)
1821 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001822 if (PyUnicode_CHECK_INTERNED(unicode))
1823 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001824 if (!PyUnicode_CheckExact(unicode))
1825 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001826#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001827 /* singleton refcount is greater than 1 */
1828 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001829#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 return 1;
1831}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001832
Victor Stinnerfe226c02011-10-03 03:52:20 +02001833static int
1834unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1835{
1836 PyObject *unicode;
1837 Py_ssize_t old_length;
1838
1839 assert(p_unicode != NULL);
1840 unicode = *p_unicode;
1841
1842 assert(unicode != NULL);
1843 assert(PyUnicode_Check(unicode));
1844 assert(0 <= length);
1845
Victor Stinner910337b2011-10-03 03:20:16 +02001846 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001847 old_length = PyUnicode_WSTR_LENGTH(unicode);
1848 else
1849 old_length = PyUnicode_GET_LENGTH(unicode);
1850 if (old_length == length)
1851 return 0;
1852
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001853 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001854 _Py_INCREF_UNICODE_EMPTY();
1855 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001856 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001857 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001858 return 0;
1859 }
1860
Victor Stinner488fa492011-12-12 00:01:39 +01001861 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001862 PyObject *copy = resize_copy(unicode, length);
1863 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001864 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001865 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001866 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001867 }
1868
Victor Stinnerfe226c02011-10-03 03:52:20 +02001869 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001870 PyObject *new_unicode = resize_compact(unicode, length);
1871 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001872 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001873 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001875 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001876 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001877}
1878
Alexander Belopolsky40018472011-02-26 01:02:56 +00001879int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001880PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001881{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001882 PyObject *unicode;
1883 if (p_unicode == NULL) {
1884 PyErr_BadInternalCall();
1885 return -1;
1886 }
1887 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001888 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001889 {
1890 PyErr_BadInternalCall();
1891 return -1;
1892 }
1893 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001894}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001895
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001896/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001897
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001898 WARNING: The function doesn't copy the terminating null character and
1899 doesn't check the maximum character (may write a latin1 character in an
1900 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001901static void
1902unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1903 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001904{
1905 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1906 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001907 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001908
1909 switch (kind) {
1910 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001911 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001912#ifdef Py_DEBUG
1913 if (PyUnicode_IS_ASCII(unicode)) {
1914 Py_UCS4 maxchar = ucs1lib_find_max_char(
1915 (const Py_UCS1*)str,
1916 (const Py_UCS1*)str + len);
1917 assert(maxchar < 128);
1918 }
1919#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001920 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001921 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001922 }
1923 case PyUnicode_2BYTE_KIND: {
1924 Py_UCS2 *start = (Py_UCS2 *)data + index;
1925 Py_UCS2 *ucs2 = start;
1926 assert(index <= PyUnicode_GET_LENGTH(unicode));
1927
Victor Stinner184252a2012-06-16 02:57:41 +02001928 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001929 *ucs2 = (Py_UCS2)*str;
1930
1931 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001932 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001933 }
1934 default: {
1935 Py_UCS4 *start = (Py_UCS4 *)data + index;
1936 Py_UCS4 *ucs4 = start;
1937 assert(kind == PyUnicode_4BYTE_KIND);
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs4 = (Py_UCS4)*str;
1942
1943 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001944 }
1945 }
1946}
1947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948static PyObject*
1949get_latin1_char(unsigned char ch)
1950{
Victor Stinnera464fc12011-10-02 20:39:30 +02001951 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001953 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 if (!unicode)
1955 return NULL;
1956 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001957 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958 unicode_latin1[ch] = unicode;
1959 }
1960 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001961 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962}
1963
Victor Stinner985a82a2014-01-03 12:53:47 +01001964static PyObject*
1965unicode_char(Py_UCS4 ch)
1966{
1967 PyObject *unicode;
1968
1969 assert(ch <= MAX_UNICODE);
1970
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001971 if (ch < 256)
1972 return get_latin1_char(ch);
1973
Victor Stinner985a82a2014-01-03 12:53:47 +01001974 unicode = PyUnicode_New(1, ch);
1975 if (unicode == NULL)
1976 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001977
1978 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1979 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001980 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001981 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001982 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1983 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1984 }
1985 assert(_PyUnicode_CheckConsistency(unicode, 1));
1986 return unicode;
1987}
1988
Alexander Belopolsky40018472011-02-26 01:02:56 +00001989PyObject *
1990PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001991{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02001992 if (u == NULL)
1993 return (PyObject*)_PyUnicode_New(size);
1994
1995 if (size < 0) {
1996 PyErr_BadInternalCall();
1997 return NULL;
1998 }
1999
2000 return PyUnicode_FromWideChar(u, size);
2001}
2002
2003PyObject *
2004PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2005{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002006 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 Py_UCS4 maxchar = 0;
2008 Py_ssize_t num_surrogates;
2009
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002010 if (u == NULL && size != 0) {
2011 PyErr_BadInternalCall();
2012 return NULL;
2013 }
2014
2015 if (size == -1) {
2016 size = wcslen(u);
2017 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002018
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002019 /* If the Unicode data is known at construction time, we can apply
2020 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002023 if (size == 0)
2024 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 /* Single character Unicode objects in the Latin-1 range are
2027 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002028 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 return get_latin1_char((unsigned char)*u);
2030
2031 /* If not empty and not single character, copy the Unicode data
2032 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002033 if (find_maxchar_surrogates(u, u + size,
2034 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 return NULL;
2036
Victor Stinner8faf8212011-12-08 22:14:11 +01002037 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002038 if (!unicode)
2039 return NULL;
2040
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 switch (PyUnicode_KIND(unicode)) {
2042 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002043 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2045 break;
2046 case PyUnicode_2BYTE_KIND:
2047#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002048 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002050 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002051 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2052#endif
2053 break;
2054 case PyUnicode_4BYTE_KIND:
2055#if SIZEOF_WCHAR_T == 2
2056 /* This is the only case which has to process surrogates, thus
2057 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002058 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059#else
2060 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002061 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002062#endif
2063 break;
2064 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002065 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002067
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002068 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002069}
2070
Alexander Belopolsky40018472011-02-26 01:02:56 +00002071PyObject *
2072PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002073{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002074 if (size < 0) {
2075 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002076 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002077 return NULL;
2078 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002079 if (u != NULL)
2080 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2081 else
2082 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002083}
2084
Alexander Belopolsky40018472011-02-26 01:02:56 +00002085PyObject *
2086PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002087{
2088 size_t size = strlen(u);
2089 if (size > PY_SSIZE_T_MAX) {
2090 PyErr_SetString(PyExc_OverflowError, "input too long");
2091 return NULL;
2092 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002093 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002094}
2095
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002096PyObject *
2097_PyUnicode_FromId(_Py_Identifier *id)
2098{
2099 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002100 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2101 strlen(id->string),
2102 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002103 if (!id->object)
2104 return NULL;
2105 PyUnicode_InternInPlace(&id->object);
2106 assert(!id->next);
2107 id->next = static_strings;
2108 static_strings = id;
2109 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002110 return id->object;
2111}
2112
2113void
2114_PyUnicode_ClearStaticStrings()
2115{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002116 _Py_Identifier *tmp, *s = static_strings;
2117 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002118 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002119 tmp = s->next;
2120 s->next = NULL;
2121 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002122 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002123 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002124}
2125
Benjamin Peterson0df54292012-03-26 14:50:32 -04002126/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002127
Victor Stinnerd3f08822012-05-29 12:57:52 +02002128PyObject*
2129_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002130{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002131 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002132 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002133 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002134#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002135 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002136#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002137 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002138 }
Victor Stinner785938e2011-12-11 20:09:03 +01002139 unicode = PyUnicode_New(size, 127);
2140 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002141 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002142 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2143 assert(_PyUnicode_CheckConsistency(unicode, 1));
2144 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002145}
2146
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002147static Py_UCS4
2148kind_maxchar_limit(unsigned int kind)
2149{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002150 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002151 case PyUnicode_1BYTE_KIND:
2152 return 0x80;
2153 case PyUnicode_2BYTE_KIND:
2154 return 0x100;
2155 case PyUnicode_4BYTE_KIND:
2156 return 0x10000;
2157 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002158 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159 }
2160}
2161
Victor Stinner702c7342011-10-05 13:50:52 +02002162static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002163_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002164{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002165 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002166 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002167
Serhiy Storchaka678db842013-01-26 12:16:36 +02002168 if (size == 0)
2169 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002170 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002171 if (size == 1)
2172 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002173
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002174 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002175 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176 if (!res)
2177 return NULL;
2178 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002179 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002181}
2182
Victor Stinnere57b1c02011-09-28 22:20:48 +02002183static PyObject*
2184_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185{
2186 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002187 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002188
Serhiy Storchaka678db842013-01-26 12:16:36 +02002189 if (size == 0)
2190 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002191 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002192 if (size == 1)
2193 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002194
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002195 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002196 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 if (!res)
2198 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002199 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002200 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002201 else {
2202 _PyUnicode_CONVERT_BYTES(
2203 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2204 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002205 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002206 return res;
2207}
2208
Victor Stinnere57b1c02011-09-28 22:20:48 +02002209static PyObject*
2210_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002211{
2212 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002213 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002214
Serhiy Storchaka678db842013-01-26 12:16:36 +02002215 if (size == 0)
2216 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002217 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002218 if (size == 1)
2219 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002220
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002221 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002222 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 if (!res)
2224 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002225 if (max_char < 256)
2226 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2227 PyUnicode_1BYTE_DATA(res));
2228 else if (max_char < 0x10000)
2229 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2230 PyUnicode_2BYTE_DATA(res));
2231 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002233 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 return res;
2235}
2236
2237PyObject*
2238PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2239{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002240 if (size < 0) {
2241 PyErr_SetString(PyExc_ValueError, "size must be positive");
2242 return NULL;
2243 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002244 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002245 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002246 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002248 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002249 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002250 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002251 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002252 PyErr_SetString(PyExc_SystemError, "invalid kind");
2253 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255}
2256
Victor Stinnerece58de2012-04-23 23:36:38 +02002257Py_UCS4
2258_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2259{
2260 enum PyUnicode_Kind kind;
2261 void *startptr, *endptr;
2262
2263 assert(PyUnicode_IS_READY(unicode));
2264 assert(0 <= start);
2265 assert(end <= PyUnicode_GET_LENGTH(unicode));
2266 assert(start <= end);
2267
2268 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2269 return PyUnicode_MAX_CHAR_VALUE(unicode);
2270
2271 if (start == end)
2272 return 127;
2273
Victor Stinner94d558b2012-04-27 22:26:58 +02002274 if (PyUnicode_IS_ASCII(unicode))
2275 return 127;
2276
Victor Stinnerece58de2012-04-23 23:36:38 +02002277 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002278 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002279 endptr = (char *)startptr + end * kind;
2280 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002281 switch(kind) {
2282 case PyUnicode_1BYTE_KIND:
2283 return ucs1lib_find_max_char(startptr, endptr);
2284 case PyUnicode_2BYTE_KIND:
2285 return ucs2lib_find_max_char(startptr, endptr);
2286 case PyUnicode_4BYTE_KIND:
2287 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002288 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002289 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002290 }
2291}
2292
Victor Stinner25a4b292011-10-06 12:31:55 +02002293/* Ensure that a string uses the most efficient storage, if it is not the
2294 case: create a new string with of the right kind. Write NULL into *p_unicode
2295 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002296static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002297unicode_adjust_maxchar(PyObject **p_unicode)
2298{
2299 PyObject *unicode, *copy;
2300 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002301 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002302 unsigned int kind;
2303
2304 assert(p_unicode != NULL);
2305 unicode = *p_unicode;
2306 assert(PyUnicode_IS_READY(unicode));
2307 if (PyUnicode_IS_ASCII(unicode))
2308 return;
2309
2310 len = PyUnicode_GET_LENGTH(unicode);
2311 kind = PyUnicode_KIND(unicode);
2312 if (kind == PyUnicode_1BYTE_KIND) {
2313 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002314 max_char = ucs1lib_find_max_char(u, u + len);
2315 if (max_char >= 128)
2316 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002317 }
2318 else if (kind == PyUnicode_2BYTE_KIND) {
2319 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002320 max_char = ucs2lib_find_max_char(u, u + len);
2321 if (max_char >= 256)
2322 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002323 }
2324 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002325 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002326 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002327 max_char = ucs4lib_find_max_char(u, u + len);
2328 if (max_char >= 0x10000)
2329 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002330 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002331 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002332 if (copy != NULL)
2333 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002334 Py_DECREF(unicode);
2335 *p_unicode = copy;
2336}
2337
Victor Stinner034f6cf2011-09-30 02:26:44 +02002338PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002339_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002340{
Victor Stinner87af4f22011-11-21 23:03:47 +01002341 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002342 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002343
Victor Stinner034f6cf2011-09-30 02:26:44 +02002344 if (!PyUnicode_Check(unicode)) {
2345 PyErr_BadInternalCall();
2346 return NULL;
2347 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002348 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002349 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002350
Victor Stinner87af4f22011-11-21 23:03:47 +01002351 length = PyUnicode_GET_LENGTH(unicode);
2352 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002353 if (!copy)
2354 return NULL;
2355 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2356
Christian Heimesf051e432016-09-13 20:22:02 +02002357 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002358 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002359 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002360 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002361}
2362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002363
Victor Stinnerbc603d12011-10-02 01:00:40 +02002364/* Widen Unicode objects to larger buffers. Don't write terminating null
2365 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002366
2367void*
2368_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2369{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002370 Py_ssize_t len;
2371 void *result;
2372 unsigned int skind;
2373
Benjamin Petersonbac79492012-01-14 13:34:47 -05002374 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002375 return NULL;
2376
2377 len = PyUnicode_GET_LENGTH(s);
2378 skind = PyUnicode_KIND(s);
2379 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002380 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002381 return NULL;
2382 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002383 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002384 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002385 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002386 if (!result)
2387 return PyErr_NoMemory();
2388 assert(skind == PyUnicode_1BYTE_KIND);
2389 _PyUnicode_CONVERT_BYTES(
2390 Py_UCS1, Py_UCS2,
2391 PyUnicode_1BYTE_DATA(s),
2392 PyUnicode_1BYTE_DATA(s) + len,
2393 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002394 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002395 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002396 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002397 if (!result)
2398 return PyErr_NoMemory();
2399 if (skind == PyUnicode_2BYTE_KIND) {
2400 _PyUnicode_CONVERT_BYTES(
2401 Py_UCS2, Py_UCS4,
2402 PyUnicode_2BYTE_DATA(s),
2403 PyUnicode_2BYTE_DATA(s) + len,
2404 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002405 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002406 else {
2407 assert(skind == PyUnicode_1BYTE_KIND);
2408 _PyUnicode_CONVERT_BYTES(
2409 Py_UCS1, Py_UCS4,
2410 PyUnicode_1BYTE_DATA(s),
2411 PyUnicode_1BYTE_DATA(s) + len,
2412 result);
2413 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002415 default:
2416 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 }
Victor Stinner01698042011-10-04 00:04:26 +02002418 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002419 return NULL;
2420}
2421
2422static Py_UCS4*
2423as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2424 int copy_null)
2425{
2426 int kind;
2427 void *data;
2428 Py_ssize_t len, targetlen;
2429 if (PyUnicode_READY(string) == -1)
2430 return NULL;
2431 kind = PyUnicode_KIND(string);
2432 data = PyUnicode_DATA(string);
2433 len = PyUnicode_GET_LENGTH(string);
2434 targetlen = len;
2435 if (copy_null)
2436 targetlen++;
2437 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002438 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 if (!target) {
2440 PyErr_NoMemory();
2441 return NULL;
2442 }
2443 }
2444 else {
2445 if (targetsize < targetlen) {
2446 PyErr_Format(PyExc_SystemError,
2447 "string is longer than the buffer");
2448 if (copy_null && 0 < targetsize)
2449 target[0] = 0;
2450 return NULL;
2451 }
2452 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002453 if (kind == PyUnicode_1BYTE_KIND) {
2454 Py_UCS1 *start = (Py_UCS1 *) data;
2455 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002457 else if (kind == PyUnicode_2BYTE_KIND) {
2458 Py_UCS2 *start = (Py_UCS2 *) data;
2459 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2460 }
2461 else {
2462 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002463 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002464 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002465 if (copy_null)
2466 target[len] = 0;
2467 return target;
2468}
2469
2470Py_UCS4*
2471PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2472 int copy_null)
2473{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002474 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 PyErr_BadInternalCall();
2476 return NULL;
2477 }
2478 return as_ucs4(string, target, targetsize, copy_null);
2479}
2480
2481Py_UCS4*
2482PyUnicode_AsUCS4Copy(PyObject *string)
2483{
2484 return as_ucs4(string, NULL, 0, 1);
2485}
2486
Victor Stinner15a11362012-10-06 23:48:20 +02002487/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002488 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2489 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2490#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002491
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002492static int
2493unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2494 Py_ssize_t width, Py_ssize_t precision)
2495{
2496 Py_ssize_t length, fill, arglen;
2497 Py_UCS4 maxchar;
2498
2499 if (PyUnicode_READY(str) == -1)
2500 return -1;
2501
2502 length = PyUnicode_GET_LENGTH(str);
2503 if ((precision == -1 || precision >= length)
2504 && width <= length)
2505 return _PyUnicodeWriter_WriteStr(writer, str);
2506
2507 if (precision != -1)
2508 length = Py_MIN(precision, length);
2509
2510 arglen = Py_MAX(length, width);
2511 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2512 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2513 else
2514 maxchar = writer->maxchar;
2515
2516 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2517 return -1;
2518
2519 if (width > length) {
2520 fill = width - length;
2521 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2522 return -1;
2523 writer->pos += fill;
2524 }
2525
2526 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2527 str, 0, length);
2528 writer->pos += length;
2529 return 0;
2530}
2531
2532static int
Victor Stinner998b8062018-09-12 00:23:25 +02002533unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002534 Py_ssize_t width, Py_ssize_t precision)
2535{
2536 /* UTF-8 */
2537 Py_ssize_t length;
2538 PyObject *unicode;
2539 int res;
2540
2541 length = strlen(str);
2542 if (precision != -1)
2543 length = Py_MIN(length, precision);
2544 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2545 if (unicode == NULL)
2546 return -1;
2547
2548 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2549 Py_DECREF(unicode);
2550 return res;
2551}
2552
Victor Stinner96865452011-03-01 23:44:09 +00002553static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002554unicode_fromformat_arg(_PyUnicodeWriter *writer,
2555 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002556{
Victor Stinnere215d962012-10-06 23:03:36 +02002557 const char *p;
2558 Py_ssize_t len;
2559 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002560 Py_ssize_t width;
2561 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002562 int longflag;
2563 int longlongflag;
2564 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002565 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002566
2567 p = f;
2568 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002569 zeropad = 0;
2570 if (*f == '0') {
2571 zeropad = 1;
2572 f++;
2573 }
Victor Stinner96865452011-03-01 23:44:09 +00002574
2575 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002576 width = -1;
2577 if (Py_ISDIGIT((unsigned)*f)) {
2578 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002579 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002580 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002581 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002582 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002583 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002584 return NULL;
2585 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002586 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002587 f++;
2588 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002589 }
2590 precision = -1;
2591 if (*f == '.') {
2592 f++;
2593 if (Py_ISDIGIT((unsigned)*f)) {
2594 precision = (*f - '0');
2595 f++;
2596 while (Py_ISDIGIT((unsigned)*f)) {
2597 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2598 PyErr_SetString(PyExc_ValueError,
2599 "precision too big");
2600 return NULL;
2601 }
2602 precision = (precision * 10) + (*f - '0');
2603 f++;
2604 }
2605 }
Victor Stinner96865452011-03-01 23:44:09 +00002606 if (*f == '%') {
2607 /* "%.3%s" => f points to "3" */
2608 f--;
2609 }
2610 }
2611 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002612 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002613 f--;
2614 }
Victor Stinner96865452011-03-01 23:44:09 +00002615
2616 /* Handle %ld, %lu, %lld and %llu. */
2617 longflag = 0;
2618 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002619 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002620 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002621 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002622 longflag = 1;
2623 ++f;
2624 }
Victor Stinner96865452011-03-01 23:44:09 +00002625 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002626 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002627 longlongflag = 1;
2628 f += 2;
2629 }
Victor Stinner96865452011-03-01 23:44:09 +00002630 }
2631 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002632 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002633 size_tflag = 1;
2634 ++f;
2635 }
Victor Stinnere215d962012-10-06 23:03:36 +02002636
2637 if (f[1] == '\0')
2638 writer->overallocate = 0;
2639
2640 switch (*f) {
2641 case 'c':
2642 {
2643 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002644 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002645 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002646 "character argument not in range(0x110000)");
2647 return NULL;
2648 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002649 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002650 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002651 break;
2652 }
2653
2654 case 'i':
2655 case 'd':
2656 case 'u':
2657 case 'x':
2658 {
2659 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002660 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002661 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002662
2663 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002664 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002665 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002666 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002667 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002668 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002669 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002670 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002671 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002672 va_arg(*vargs, size_t));
2673 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002674 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002675 va_arg(*vargs, unsigned int));
2676 }
2677 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002678 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002679 }
2680 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002681 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002682 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002683 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002684 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002685 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002686 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002687 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002688 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002689 va_arg(*vargs, Py_ssize_t));
2690 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002691 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002692 va_arg(*vargs, int));
2693 }
2694 assert(len >= 0);
2695
Victor Stinnere215d962012-10-06 23:03:36 +02002696 if (precision < len)
2697 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002698
2699 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002700 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2701 return NULL;
2702
Victor Stinnere215d962012-10-06 23:03:36 +02002703 if (width > precision) {
2704 Py_UCS4 fillchar;
2705 fill = width - precision;
2706 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002707 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2708 return NULL;
2709 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002710 }
Victor Stinner15a11362012-10-06 23:48:20 +02002711 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002712 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002713 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2714 return NULL;
2715 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002716 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002717
Victor Stinner4a587072013-11-19 12:54:53 +01002718 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2719 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002720 break;
2721 }
2722
2723 case 'p':
2724 {
2725 char number[MAX_LONG_LONG_CHARS];
2726
2727 len = sprintf(number, "%p", va_arg(*vargs, void*));
2728 assert(len >= 0);
2729
2730 /* %p is ill-defined: ensure leading 0x. */
2731 if (number[1] == 'X')
2732 number[1] = 'x';
2733 else if (number[1] != 'x') {
2734 memmove(number + 2, number,
2735 strlen(number) + 1);
2736 number[0] = '0';
2737 number[1] = 'x';
2738 len += 2;
2739 }
2740
Victor Stinner4a587072013-11-19 12:54:53 +01002741 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002742 return NULL;
2743 break;
2744 }
2745
2746 case 's':
2747 {
2748 /* UTF-8 */
2749 const char *s = va_arg(*vargs, const char*);
Victor Stinner998b8062018-09-12 00:23:25 +02002750 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002751 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002752 break;
2753 }
2754
2755 case 'U':
2756 {
2757 PyObject *obj = va_arg(*vargs, PyObject *);
2758 assert(obj && _PyUnicode_CHECK(obj));
2759
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002760 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002761 return NULL;
2762 break;
2763 }
2764
2765 case 'V':
2766 {
2767 PyObject *obj = va_arg(*vargs, PyObject *);
2768 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002769 if (obj) {
2770 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002771 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002772 return NULL;
2773 }
2774 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002775 assert(str != NULL);
Victor Stinner998b8062018-09-12 00:23:25 +02002776 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002777 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002778 }
2779 break;
2780 }
2781
2782 case 'S':
2783 {
2784 PyObject *obj = va_arg(*vargs, PyObject *);
2785 PyObject *str;
2786 assert(obj);
2787 str = PyObject_Str(obj);
2788 if (!str)
2789 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002790 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002791 Py_DECREF(str);
2792 return NULL;
2793 }
2794 Py_DECREF(str);
2795 break;
2796 }
2797
2798 case 'R':
2799 {
2800 PyObject *obj = va_arg(*vargs, PyObject *);
2801 PyObject *repr;
2802 assert(obj);
2803 repr = PyObject_Repr(obj);
2804 if (!repr)
2805 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002806 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002807 Py_DECREF(repr);
2808 return NULL;
2809 }
2810 Py_DECREF(repr);
2811 break;
2812 }
2813
2814 case 'A':
2815 {
2816 PyObject *obj = va_arg(*vargs, PyObject *);
2817 PyObject *ascii;
2818 assert(obj);
2819 ascii = PyObject_ASCII(obj);
2820 if (!ascii)
2821 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002822 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002823 Py_DECREF(ascii);
2824 return NULL;
2825 }
2826 Py_DECREF(ascii);
2827 break;
2828 }
2829
2830 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002831 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002832 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002833 break;
2834
2835 default:
2836 /* if we stumble upon an unknown formatting code, copy the rest
2837 of the format string to the output string. (we cannot just
2838 skip the code, since there's no way to know what's in the
2839 argument list) */
2840 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002841 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002842 return NULL;
2843 f = p+len;
2844 return f;
2845 }
2846
2847 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002848 return f;
2849}
2850
Walter Dörwaldd2034312007-05-18 16:29:38 +00002851PyObject *
2852PyUnicode_FromFormatV(const char *format, va_list vargs)
2853{
Victor Stinnere215d962012-10-06 23:03:36 +02002854 va_list vargs2;
2855 const char *f;
2856 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002857
Victor Stinner8f674cc2013-04-17 23:02:17 +02002858 _PyUnicodeWriter_Init(&writer);
2859 writer.min_length = strlen(format) + 100;
2860 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002861
Benjamin Peterson0c212142016-09-20 20:39:33 -07002862 // Copy varags to be able to pass a reference to a subfunction.
2863 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002864
2865 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002866 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002867 f = unicode_fromformat_arg(&writer, f, &vargs2);
2868 if (f == NULL)
2869 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002871 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002872 const char *p;
2873 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002874
Victor Stinnere215d962012-10-06 23:03:36 +02002875 p = f;
2876 do
2877 {
2878 if ((unsigned char)*p > 127) {
2879 PyErr_Format(PyExc_ValueError,
2880 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2881 "string, got a non-ASCII byte: 0x%02x",
2882 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002883 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002884 }
2885 p++;
2886 }
2887 while (*p != '\0' && *p != '%');
2888 len = p - f;
2889
2890 if (*p == '\0')
2891 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002892
2893 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002894 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002895
2896 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002897 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002898 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002899 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002900 return _PyUnicodeWriter_Finish(&writer);
2901
2902 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002903 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002904 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002905 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002906}
2907
Walter Dörwaldd2034312007-05-18 16:29:38 +00002908PyObject *
2909PyUnicode_FromFormat(const char *format, ...)
2910{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002911 PyObject* ret;
2912 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002913
2914#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002915 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002916#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002919 ret = PyUnicode_FromFormatV(format, vargs);
2920 va_end(vargs);
2921 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002922}
2923
Serhiy Storchakac46db922018-10-23 22:58:24 +03002924static Py_ssize_t
2925unicode_get_widechar_size(PyObject *unicode)
2926{
2927 Py_ssize_t res;
2928
2929 assert(unicode != NULL);
2930 assert(_PyUnicode_CHECK(unicode));
2931
2932 if (_PyUnicode_WSTR(unicode) != NULL) {
2933 return PyUnicode_WSTR_LENGTH(unicode);
2934 }
2935 assert(PyUnicode_IS_READY(unicode));
2936
2937 res = _PyUnicode_LENGTH(unicode);
2938#if SIZEOF_WCHAR_T == 2
2939 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
2940 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
2941 const Py_UCS4 *end = s + res;
2942 for (; s < end; ++s) {
2943 if (*s > 0xFFFF) {
2944 ++res;
2945 }
2946 }
2947 }
2948#endif
2949 return res;
2950}
2951
2952static void
2953unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
2954{
2955 const wchar_t *wstr;
2956
2957 assert(unicode != NULL);
2958 assert(_PyUnicode_CHECK(unicode));
2959
2960 wstr = _PyUnicode_WSTR(unicode);
2961 if (wstr != NULL) {
2962 memcpy(w, wstr, size * sizeof(wchar_t));
2963 return;
2964 }
2965 assert(PyUnicode_IS_READY(unicode));
2966
2967 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
2968 const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
2969 for (; size--; ++s, ++w) {
2970 *w = *s;
2971 }
2972 }
2973 else {
2974#if SIZEOF_WCHAR_T == 4
2975 assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
2976 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
2977 for (; size--; ++s, ++w) {
2978 *w = *s;
2979 }
2980#else
2981 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2982 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
2983 for (; size--; ++s, ++w) {
2984 Py_UCS4 ch = *s;
2985 if (ch > 0xFFFF) {
2986 assert(ch <= MAX_UNICODE);
2987 /* encode surrogate pair in this case */
2988 *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
2989 if (!size--)
2990 break;
2991 *w = Py_UNICODE_LOW_SURROGATE(ch);
2992 }
2993 else {
2994 *w = ch;
2995 }
2996 }
2997#endif
2998 }
2999}
3000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003001#ifdef HAVE_WCHAR_H
3002
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003003/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00003004
Victor Stinnerd88d9832011-09-06 02:00:05 +02003005 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003006 character) required to convert the unicode object. Ignore size argument.
3007
Victor Stinnerd88d9832011-09-06 02:00:05 +02003008 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003009 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02003010 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003011Py_ssize_t
3012PyUnicode_AsWideChar(PyObject *unicode,
3013 wchar_t *w,
3014 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00003015{
Victor Stinner5593d8a2010-10-02 11:11:27 +00003016 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003017
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003018 if (unicode == NULL) {
3019 PyErr_BadInternalCall();
3020 return -1;
3021 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003022 if (!PyUnicode_Check(unicode)) {
3023 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003024 return -1;
Victor Stinner5593d8a2010-10-02 11:11:27 +00003025 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003026
3027 res = unicode_get_widechar_size(unicode);
3028 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003029 return res + 1;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003030 }
3031
3032 if (size > res) {
3033 size = res + 1;
3034 }
3035 else {
3036 res = size;
3037 }
3038 unicode_copy_as_widechar(unicode, w, size);
3039 return res;
Victor Stinner137c34c2010-09-29 10:25:54 +00003040}
3041
Victor Stinner137c34c2010-09-29 10:25:54 +00003042wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003043PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003044 Py_ssize_t *size)
3045{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003046 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003047 Py_ssize_t buflen;
3048
3049 if (unicode == NULL) {
3050 PyErr_BadInternalCall();
3051 return NULL;
3052 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003053 if (!PyUnicode_Check(unicode)) {
3054 PyErr_BadArgument();
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003055 return NULL;
3056 }
3057
Serhiy Storchakac46db922018-10-23 22:58:24 +03003058 buflen = unicode_get_widechar_size(unicode);
3059 buffer = (wchar_t *) PyMem_NEW(wchar_t, (buflen + 1));
Victor Stinner137c34c2010-09-29 10:25:54 +00003060 if (buffer == NULL) {
3061 PyErr_NoMemory();
3062 return NULL;
3063 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003064 unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3065 if (size != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00003066 *size = buflen;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003067 }
3068 else if (wcslen(buffer) != (size_t)buflen) {
3069 PyMem_FREE(buffer);
3070 PyErr_SetString(PyExc_ValueError,
3071 "embedded null character");
3072 return NULL;
3073 }
Victor Stinner137c34c2010-09-29 10:25:54 +00003074 return buffer;
3075}
3076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003077#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003078
Alexander Belopolsky40018472011-02-26 01:02:56 +00003079PyObject *
3080PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003081{
Victor Stinner8faf8212011-12-08 22:14:11 +01003082 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003083 PyErr_SetString(PyExc_ValueError,
3084 "chr() arg not in range(0x110000)");
3085 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003086 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003087
Victor Stinner985a82a2014-01-03 12:53:47 +01003088 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003089}
3090
Alexander Belopolsky40018472011-02-26 01:02:56 +00003091PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003092PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003093{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003094 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003095 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003096 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003097 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003098 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003099 Py_INCREF(obj);
3100 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003101 }
3102 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003103 /* For a Unicode subtype that's not a Unicode object,
3104 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003105 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003106 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003107 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003108 "Can't convert '%.100s' object to str implicitly",
3109 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003110 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003111}
3112
Alexander Belopolsky40018472011-02-26 01:02:56 +00003113PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003114PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003115 const char *encoding,
3116 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003117{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003118 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003119 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003120
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003122 PyErr_BadInternalCall();
3123 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003124 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003125
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003126 /* Decoding bytes objects is the most common case and should be fast */
3127 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003128 if (PyBytes_GET_SIZE(obj) == 0)
3129 _Py_RETURN_UNICODE_EMPTY();
3130 v = PyUnicode_Decode(
3131 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3132 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003133 return v;
3134 }
3135
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003136 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003137 PyErr_SetString(PyExc_TypeError,
3138 "decoding str is not supported");
3139 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003140 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003141
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003142 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3143 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3144 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003145 "decoding to str: need a bytes-like object, %.80s found",
3146 Py_TYPE(obj)->tp_name);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003147 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003148 }
Tim Petersced69f82003-09-16 20:30:58 +00003149
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003150 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003151 PyBuffer_Release(&buffer);
3152 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003153 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003154
Serhiy Storchaka05997252013-01-26 12:14:02 +02003155 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003156 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003157 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003158}
3159
Victor Stinnerebe17e02016-10-12 13:57:45 +02003160/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3161 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3162 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003163int
3164_Py_normalize_encoding(const char *encoding,
3165 char *lower,
3166 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003167{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003168 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003169 char *l;
3170 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003171 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003172
Victor Stinner942889a2016-09-05 15:40:10 -07003173 assert(encoding != NULL);
3174
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003175 e = encoding;
3176 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003177 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003178 punct = 0;
3179 while (1) {
3180 char c = *e;
3181 if (c == 0) {
3182 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003183 }
Victor Stinner942889a2016-09-05 15:40:10 -07003184
3185 if (Py_ISALNUM(c) || c == '.') {
3186 if (punct && l != lower) {
3187 if (l == l_end) {
3188 return 0;
3189 }
3190 *l++ = '_';
3191 }
3192 punct = 0;
3193
3194 if (l == l_end) {
3195 return 0;
3196 }
3197 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003198 }
3199 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003200 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003201 }
Victor Stinner942889a2016-09-05 15:40:10 -07003202
3203 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003204 }
3205 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003206 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003207}
3208
Alexander Belopolsky40018472011-02-26 01:02:56 +00003209PyObject *
3210PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003211 Py_ssize_t size,
3212 const char *encoding,
3213 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003214{
3215 PyObject *buffer = NULL, *unicode;
3216 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003217 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3218
3219 if (encoding == NULL) {
3220 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3221 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003222
Fred Drakee4315f52000-05-09 19:53:39 +00003223 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003224 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3225 char *lower = buflower;
3226
3227 /* Fast paths */
3228 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3229 lower += 3;
3230 if (*lower == '_') {
3231 /* Match "utf8" and "utf_8" */
3232 lower++;
3233 }
3234
3235 if (lower[0] == '8' && lower[1] == 0) {
3236 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3237 }
3238 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3239 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3240 }
3241 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3242 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3243 }
3244 }
3245 else {
3246 if (strcmp(lower, "ascii") == 0
3247 || strcmp(lower, "us_ascii") == 0) {
3248 return PyUnicode_DecodeASCII(s, size, errors);
3249 }
Steve Dowercc16be82016-09-08 10:35:16 -07003250 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003251 else if (strcmp(lower, "mbcs") == 0) {
3252 return PyUnicode_DecodeMBCS(s, size, errors);
3253 }
3254 #endif
3255 else if (strcmp(lower, "latin1") == 0
3256 || strcmp(lower, "latin_1") == 0
3257 || strcmp(lower, "iso_8859_1") == 0
3258 || strcmp(lower, "iso8859_1") == 0) {
3259 return PyUnicode_DecodeLatin1(s, size, errors);
3260 }
3261 }
Victor Stinner37296e82010-06-10 13:36:23 +00003262 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003263
3264 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003265 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003266 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003267 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003268 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003269 if (buffer == NULL)
3270 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003271 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003272 if (unicode == NULL)
3273 goto onError;
3274 if (!PyUnicode_Check(unicode)) {
3275 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003276 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003277 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003278 encoding,
3279 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003280 Py_DECREF(unicode);
3281 goto onError;
3282 }
3283 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003284 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003285
Benjamin Peterson29060642009-01-31 22:14:21 +00003286 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003287 Py_XDECREF(buffer);
3288 return NULL;
3289}
3290
Alexander Belopolsky40018472011-02-26 01:02:56 +00003291PyObject *
3292PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003293 const char *encoding,
3294 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003295{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003296 if (!PyUnicode_Check(unicode)) {
3297 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003298 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003299 }
3300
Serhiy Storchaka00939072016-10-27 21:05:49 +03003301 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3302 "PyUnicode_AsDecodedObject() is deprecated; "
3303 "use PyCodec_Decode() to decode from str", 1) < 0)
3304 return NULL;
3305
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003306 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003307 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003308
3309 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003310 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003311}
3312
Alexander Belopolsky40018472011-02-26 01:02:56 +00003313PyObject *
3314PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003315 const char *encoding,
3316 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003317{
3318 PyObject *v;
3319
3320 if (!PyUnicode_Check(unicode)) {
3321 PyErr_BadArgument();
3322 goto onError;
3323 }
3324
Serhiy Storchaka00939072016-10-27 21:05:49 +03003325 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3326 "PyUnicode_AsDecodedUnicode() is deprecated; "
3327 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3328 return NULL;
3329
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003330 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003331 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003332
3333 /* Decode via the codec registry */
3334 v = PyCodec_Decode(unicode, encoding, errors);
3335 if (v == NULL)
3336 goto onError;
3337 if (!PyUnicode_Check(v)) {
3338 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003339 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003340 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003341 encoding,
3342 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003343 Py_DECREF(v);
3344 goto onError;
3345 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003346 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003347
Benjamin Peterson29060642009-01-31 22:14:21 +00003348 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003349 return NULL;
3350}
3351
Alexander Belopolsky40018472011-02-26 01:02:56 +00003352PyObject *
3353PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003354 Py_ssize_t size,
3355 const char *encoding,
3356 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003357{
3358 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003359
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003360 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003361 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003362 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003363 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3364 Py_DECREF(unicode);
3365 return v;
3366}
3367
Alexander Belopolsky40018472011-02-26 01:02:56 +00003368PyObject *
3369PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003370 const char *encoding,
3371 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003372{
3373 PyObject *v;
3374
3375 if (!PyUnicode_Check(unicode)) {
3376 PyErr_BadArgument();
3377 goto onError;
3378 }
3379
Serhiy Storchaka00939072016-10-27 21:05:49 +03003380 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3381 "PyUnicode_AsEncodedObject() is deprecated; "
3382 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3383 "or PyCodec_Encode() for generic encoding", 1) < 0)
3384 return NULL;
3385
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003386 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003387 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003388
3389 /* Encode via the codec registry */
3390 v = PyCodec_Encode(unicode, encoding, errors);
3391 if (v == NULL)
3392 goto onError;
3393 return v;
3394
Benjamin Peterson29060642009-01-31 22:14:21 +00003395 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003396 return NULL;
3397}
3398
Victor Stinner1b579672011-12-17 05:47:23 +01003399
Victor Stinner2cba6b82018-01-10 22:46:15 +01003400static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003401unicode_encode_locale(PyObject *unicode, const char *errors,
3402 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003403{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003404 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003405
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003406 Py_ssize_t wlen;
3407 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3408 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003409 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003410 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003411
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003412 Py_ssize_t wlen2 = wcslen(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003413 if (wlen2 != wlen) {
3414 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003415 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003416 return NULL;
3417 }
3418
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003419 char *str;
3420 size_t error_pos;
3421 const char *reason;
3422 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003423 current_locale, error_handler);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003424 if (res != 0) {
3425 if (res == -2) {
3426 PyObject *exc;
3427 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3428 "locale", unicode,
3429 (Py_ssize_t)error_pos,
3430 (Py_ssize_t)(error_pos+1),
3431 reason);
3432 if (exc != NULL) {
3433 PyCodec_StrictErrors(exc);
3434 Py_DECREF(exc);
3435 }
3436 return NULL;
Victor Stinner2cba6b82018-01-10 22:46:15 +01003437 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003438 else if (res == -3) {
3439 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3440 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003441 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003442 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003443 PyMem_Free(wstr);
3444 return NULL;
3445 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003446 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003447 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003448
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003449 PyObject *bytes = PyBytes_FromString(str);
3450 PyMem_RawFree(str);
3451 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003452}
3453
Victor Stinnerad158722010-10-27 00:25:46 +00003454PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003455PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3456{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003457 return unicode_encode_locale(unicode, errors, 1);
3458}
3459
3460PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003461PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003462{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003463 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003464 const _PyCoreConfig *config = &interp->core_config;
3465#if defined(__APPLE__)
3466 return _PyUnicode_AsUTF8String(unicode, config->filesystem_errors);
3467#else
Victor Stinner793b5312011-04-27 00:24:21 +02003468 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3469 cannot use it to encode and decode filenames before it is loaded. Load
3470 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003471 implementation of the locale codec until the codec registry is
3472 initialized and the Python codec is loaded. See initfsencoding(). */
3473 if (interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003474 return PyUnicode_AsEncodedString(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003475 config->filesystem_encoding,
3476 config->filesystem_errors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003477 }
3478 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003479 return unicode_encode_locale(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003480 config->filesystem_errors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003481 }
Victor Stinnerad158722010-10-27 00:25:46 +00003482#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003483}
3484
Alexander Belopolsky40018472011-02-26 01:02:56 +00003485PyObject *
3486PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003487 const char *encoding,
3488 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003489{
3490 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003491 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003492
Guido van Rossumd57fd912000-03-10 22:53:23 +00003493 if (!PyUnicode_Check(unicode)) {
3494 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003495 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003496 }
Fred Drakee4315f52000-05-09 19:53:39 +00003497
Victor Stinner942889a2016-09-05 15:40:10 -07003498 if (encoding == NULL) {
3499 return _PyUnicode_AsUTF8String(unicode, errors);
3500 }
3501
Fred Drakee4315f52000-05-09 19:53:39 +00003502 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003503 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3504 char *lower = buflower;
3505
3506 /* Fast paths */
3507 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3508 lower += 3;
3509 if (*lower == '_') {
3510 /* Match "utf8" and "utf_8" */
3511 lower++;
3512 }
3513
3514 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003515 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003516 }
3517 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3518 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3519 }
3520 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3521 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3522 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003523 }
Victor Stinner942889a2016-09-05 15:40:10 -07003524 else {
3525 if (strcmp(lower, "ascii") == 0
3526 || strcmp(lower, "us_ascii") == 0) {
3527 return _PyUnicode_AsASCIIString(unicode, errors);
3528 }
Steve Dowercc16be82016-09-08 10:35:16 -07003529#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003530 else if (strcmp(lower, "mbcs") == 0) {
3531 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3532 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003533#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003534 else if (strcmp(lower, "latin1") == 0 ||
3535 strcmp(lower, "latin_1") == 0 ||
3536 strcmp(lower, "iso_8859_1") == 0 ||
3537 strcmp(lower, "iso8859_1") == 0) {
3538 return _PyUnicode_AsLatin1String(unicode, errors);
3539 }
3540 }
Victor Stinner37296e82010-06-10 13:36:23 +00003541 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003542
3543 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003544 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003545 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003546 return NULL;
3547
3548 /* The normal path */
3549 if (PyBytes_Check(v))
3550 return v;
3551
3552 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003553 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003554 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003555 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003556
3557 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003558 "encoder %s returned bytearray instead of bytes; "
3559 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003560 encoding);
3561 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003562 Py_DECREF(v);
3563 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003564 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003565
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003566 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3567 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003568 Py_DECREF(v);
3569 return b;
3570 }
3571
3572 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003573 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003574 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003575 encoding,
3576 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003577 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003578 return NULL;
3579}
3580
Alexander Belopolsky40018472011-02-26 01:02:56 +00003581PyObject *
3582PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003583 const char *encoding,
3584 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003585{
3586 PyObject *v;
3587
3588 if (!PyUnicode_Check(unicode)) {
3589 PyErr_BadArgument();
3590 goto onError;
3591 }
3592
Serhiy Storchaka00939072016-10-27 21:05:49 +03003593 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3594 "PyUnicode_AsEncodedUnicode() is deprecated; "
3595 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3596 return NULL;
3597
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003598 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003599 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003600
3601 /* Encode via the codec registry */
3602 v = PyCodec_Encode(unicode, encoding, errors);
3603 if (v == NULL)
3604 goto onError;
3605 if (!PyUnicode_Check(v)) {
3606 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003607 "'%.400s' encoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003608 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003609 encoding,
3610 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003611 Py_DECREF(v);
3612 goto onError;
3613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003614 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003615
Benjamin Peterson29060642009-01-31 22:14:21 +00003616 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003617 return NULL;
3618}
3619
Victor Stinner2cba6b82018-01-10 22:46:15 +01003620static PyObject*
3621unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3622 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003623{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003624 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003625
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003626 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3627 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003628 return NULL;
3629 }
3630
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003631 wchar_t *wstr;
3632 size_t wlen;
3633 const char *reason;
3634 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003635 current_locale, error_handler);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003636 if (res != 0) {
3637 if (res == -2) {
3638 PyObject *exc;
3639 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3640 "locale", str, len,
3641 (Py_ssize_t)wlen,
3642 (Py_ssize_t)(wlen + 1),
3643 reason);
3644 if (exc != NULL) {
3645 PyCodec_StrictErrors(exc);
3646 Py_DECREF(exc);
3647 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003648 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003649 else if (res == -3) {
3650 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3651 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003652 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003653 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003654 }
Victor Stinner2f197072011-12-17 07:08:30 +01003655 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003656 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003657
3658 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3659 PyMem_RawFree(wstr);
3660 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003661}
3662
3663PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003664PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3665 const char *errors)
3666{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003667 return unicode_decode_locale(str, len, errors, 1);
3668}
3669
3670PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003671PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003672{
3673 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003674 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003675}
3676
3677
3678PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003679PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003680 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003681 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3682}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003683
Christian Heimes5894ba72007-11-04 11:43:14 +00003684PyObject*
3685PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3686{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003687 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003688 const _PyCoreConfig *config = &interp->core_config;
3689#if defined(__APPLE__)
3690 return PyUnicode_DecodeUTF8Stateful(s, size, config->filesystem_errors, NULL);
3691#else
Victor Stinner793b5312011-04-27 00:24:21 +02003692 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3693 cannot use it to encode and decode filenames before it is loaded. Load
3694 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003695 implementation of the locale codec until the codec registry is
3696 initialized and the Python codec is loaded. See initfsencoding(). */
3697 if (interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003698 return PyUnicode_Decode(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003699 config->filesystem_encoding,
3700 config->filesystem_errors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003701 }
3702 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003703 return unicode_decode_locale(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003704 config->filesystem_errors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003705 }
Victor Stinnerad158722010-10-27 00:25:46 +00003706#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003707}
3708
Martin v. Löwis011e8422009-05-05 04:43:17 +00003709
3710int
3711PyUnicode_FSConverter(PyObject* arg, void* addr)
3712{
Brett Cannonec6ce872016-09-06 15:50:29 -07003713 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003714 PyObject *output = NULL;
3715 Py_ssize_t size;
3716 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003717 if (arg == NULL) {
3718 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003719 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003720 return 1;
3721 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003722 path = PyOS_FSPath(arg);
3723 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003724 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003725 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003726 if (PyBytes_Check(path)) {
3727 output = path;
3728 }
3729 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3730 output = PyUnicode_EncodeFSDefault(path);
3731 Py_DECREF(path);
3732 if (!output) {
3733 return 0;
3734 }
3735 assert(PyBytes_Check(output));
3736 }
3737
Victor Stinner0ea2a462010-04-30 00:22:08 +00003738 size = PyBytes_GET_SIZE(output);
3739 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003740 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003741 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003742 Py_DECREF(output);
3743 return 0;
3744 }
3745 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003746 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003747}
3748
3749
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003750int
3751PyUnicode_FSDecoder(PyObject* arg, void* addr)
3752{
Brett Cannona5711202016-09-06 19:36:01 -07003753 int is_buffer = 0;
3754 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003755 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003756 if (arg == NULL) {
3757 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003758 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003759 return 1;
3760 }
Brett Cannona5711202016-09-06 19:36:01 -07003761
3762 is_buffer = PyObject_CheckBuffer(arg);
3763 if (!is_buffer) {
3764 path = PyOS_FSPath(arg);
3765 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003766 return 0;
3767 }
Brett Cannona5711202016-09-06 19:36:01 -07003768 }
3769 else {
3770 path = arg;
3771 Py_INCREF(arg);
3772 }
3773
3774 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003775 output = path;
3776 }
3777 else if (PyBytes_Check(path) || is_buffer) {
3778 PyObject *path_bytes = NULL;
3779
3780 if (!PyBytes_Check(path) &&
3781 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Victor Stinner998b8062018-09-12 00:23:25 +02003782 "path should be string, bytes, or os.PathLike, not %.200s",
3783 Py_TYPE(arg)->tp_name)) {
3784 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003785 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003786 }
3787 path_bytes = PyBytes_FromObject(path);
3788 Py_DECREF(path);
3789 if (!path_bytes) {
3790 return 0;
3791 }
3792 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3793 PyBytes_GET_SIZE(path_bytes));
3794 Py_DECREF(path_bytes);
3795 if (!output) {
3796 return 0;
3797 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003798 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003799 else {
3800 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003801 "path should be string, bytes, or os.PathLike, not %.200s",
3802 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003803 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003804 return 0;
3805 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003806 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003807 Py_DECREF(output);
3808 return 0;
3809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003810 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003811 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003812 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003813 Py_DECREF(output);
3814 return 0;
3815 }
3816 *(PyObject**)addr = output;
3817 return Py_CLEANUP_SUPPORTED;
3818}
3819
3820
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003821const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003823{
Christian Heimesf3863112007-11-22 07:46:41 +00003824 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003825
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003826 if (!PyUnicode_Check(unicode)) {
3827 PyErr_BadArgument();
3828 return NULL;
3829 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003830 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003831 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003832
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003833 if (PyUnicode_UTF8(unicode) == NULL) {
3834 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003835 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 if (bytes == NULL)
3837 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003838 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3839 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003840 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 Py_DECREF(bytes);
3842 return NULL;
3843 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003844 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003845 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003846 PyBytes_AS_STRING(bytes),
3847 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003848 Py_DECREF(bytes);
3849 }
3850
3851 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003852 *psize = PyUnicode_UTF8_LENGTH(unicode);
3853 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003854}
3855
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003856const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003857PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3860}
3861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862Py_UNICODE *
3863PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3864{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 if (!PyUnicode_Check(unicode)) {
3866 PyErr_BadArgument();
3867 return NULL;
3868 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003869 Py_UNICODE *w = _PyUnicode_WSTR(unicode);
3870 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871 /* Non-ASCII compact unicode object */
Serhiy Storchakac46db922018-10-23 22:58:24 +03003872 assert(_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874
Serhiy Storchakac46db922018-10-23 22:58:24 +03003875 Py_ssize_t wlen = unicode_get_widechar_size(unicode);
3876 if ((size_t)wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3877 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003879 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003880 w = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (wlen + 1));
3881 if (w == NULL) {
3882 PyErr_NoMemory();
3883 return NULL;
3884 }
3885 unicode_copy_as_widechar(unicode, w, wlen + 1);
3886 _PyUnicode_WSTR(unicode) = w;
3887 if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
3888 _PyUnicode_WSTR_LENGTH(unicode) = wlen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 }
3890 }
3891 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003892 *size = PyUnicode_WSTR_LENGTH(unicode);
Serhiy Storchakac46db922018-10-23 22:58:24 +03003893 return w;
Martin v. Löwis5b222132007-06-10 09:51:05 +00003894}
3895
Alexander Belopolsky40018472011-02-26 01:02:56 +00003896Py_UNICODE *
3897PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003898{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003900}
3901
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003902const Py_UNICODE *
3903_PyUnicode_AsUnicode(PyObject *unicode)
3904{
3905 Py_ssize_t size;
3906 const Py_UNICODE *wstr;
3907
3908 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3909 if (wstr && wcslen(wstr) != (size_t)size) {
3910 PyErr_SetString(PyExc_ValueError, "embedded null character");
3911 return NULL;
3912 }
3913 return wstr;
3914}
3915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916
Alexander Belopolsky40018472011-02-26 01:02:56 +00003917Py_ssize_t
3918PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003919{
3920 if (!PyUnicode_Check(unicode)) {
3921 PyErr_BadArgument();
3922 goto onError;
3923 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003924 if (_PyUnicode_WSTR(unicode) == NULL) {
3925 if (PyUnicode_AsUnicode(unicode) == NULL)
3926 goto onError;
3927 }
3928 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003929
Benjamin Peterson29060642009-01-31 22:14:21 +00003930 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003931 return -1;
3932}
3933
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934Py_ssize_t
3935PyUnicode_GetLength(PyObject *unicode)
3936{
Victor Stinner07621332012-06-16 04:53:46 +02003937 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 PyErr_BadArgument();
3939 return -1;
3940 }
Victor Stinner07621332012-06-16 04:53:46 +02003941 if (PyUnicode_READY(unicode) == -1)
3942 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 return PyUnicode_GET_LENGTH(unicode);
3944}
3945
3946Py_UCS4
3947PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3948{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003949 void *data;
3950 int kind;
3951
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003952 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003953 PyErr_BadArgument();
3954 return (Py_UCS4)-1;
3955 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003956 if (PyUnicode_READY(unicode) == -1) {
3957 return (Py_UCS4)-1;
3958 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003959 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003960 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 return (Py_UCS4)-1;
3962 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003963 data = PyUnicode_DATA(unicode);
3964 kind = PyUnicode_KIND(unicode);
3965 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003966}
3967
3968int
3969PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3970{
3971 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003972 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003973 return -1;
3974 }
Victor Stinner488fa492011-12-12 00:01:39 +01003975 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003976 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003977 PyErr_SetString(PyExc_IndexError, "string index out of range");
3978 return -1;
3979 }
Victor Stinner488fa492011-12-12 00:01:39 +01003980 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003981 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003982 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3983 PyErr_SetString(PyExc_ValueError, "character out of range");
3984 return -1;
3985 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003986 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3987 index, ch);
3988 return 0;
3989}
3990
Alexander Belopolsky40018472011-02-26 01:02:56 +00003991const char *
3992PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003993{
Victor Stinner42cb4622010-09-01 19:39:01 +00003994 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003995}
3996
Victor Stinner554f3f02010-06-16 23:33:54 +00003997/* create or adjust a UnicodeDecodeError */
3998static void
3999make_decode_exception(PyObject **exceptionObject,
4000 const char *encoding,
4001 const char *input, Py_ssize_t length,
4002 Py_ssize_t startpos, Py_ssize_t endpos,
4003 const char *reason)
4004{
4005 if (*exceptionObject == NULL) {
4006 *exceptionObject = PyUnicodeDecodeError_Create(
4007 encoding, input, length, startpos, endpos, reason);
4008 }
4009 else {
4010 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4011 goto onError;
4012 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4013 goto onError;
4014 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4015 goto onError;
4016 }
4017 return;
4018
4019onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004020 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004021}
4022
Steve Dowercc16be82016-09-08 10:35:16 -07004023#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004024/* error handling callback helper:
4025 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004026 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027 and adjust various state variables.
4028 return 0 on success, -1 on error
4029*/
4030
Alexander Belopolsky40018472011-02-26 01:02:56 +00004031static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004032unicode_decode_call_errorhandler_wchar(
4033 const char *errors, PyObject **errorHandler,
4034 const char *encoding, const char *reason,
4035 const char **input, const char **inend, Py_ssize_t *startinpos,
4036 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4037 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004038{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004039 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004040
4041 PyObject *restuple = NULL;
4042 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004043 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004044 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004045 Py_ssize_t requiredsize;
4046 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004047 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004048 wchar_t *repwstr;
4049 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004050
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004051 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4052 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004053
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004054 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 *errorHandler = PyCodec_LookupError(errors);
4056 if (*errorHandler == NULL)
4057 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004058 }
4059
Victor Stinner554f3f02010-06-16 23:33:54 +00004060 make_decode_exception(exceptionObject,
4061 encoding,
4062 *input, *inend - *input,
4063 *startinpos, *endinpos,
4064 reason);
4065 if (*exceptionObject == NULL)
4066 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004067
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004068 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004070 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004071 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004072 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004073 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004074 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004075 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004076 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004077
4078 /* Copy back the bytes variables, which might have been modified by the
4079 callback */
4080 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4081 if (!inputobj)
4082 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004083 *input = PyBytes_AS_STRING(inputobj);
4084 insize = PyBytes_GET_SIZE(inputobj);
4085 *inend = *input + insize;
4086 /* we can DECREF safely, as the exception has another reference,
4087 so the object won't go away. */
4088 Py_DECREF(inputobj);
4089
4090 if (newpos<0)
4091 newpos = insize+newpos;
4092 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004093 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004094 goto onError;
4095 }
4096
4097 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4098 if (repwstr == NULL)
4099 goto onError;
4100 /* need more space? (at least enough for what we
4101 have+the replacement+the rest of the string (starting
4102 at the new input position), so we won't have to check space
4103 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004104 requiredsize = *outpos;
4105 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4106 goto overflow;
4107 requiredsize += repwlen;
4108 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4109 goto overflow;
4110 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004111 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004112 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004113 requiredsize = 2*outsize;
4114 if (unicode_resize(output, requiredsize) < 0)
4115 goto onError;
4116 }
4117 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4118 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004119 *endinpos = newpos;
4120 *inptr = *input + newpos;
4121
4122 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004123 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004124 return 0;
4125
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004126 overflow:
4127 PyErr_SetString(PyExc_OverflowError,
4128 "decoded result is too long for a Python string");
4129
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004130 onError:
4131 Py_XDECREF(restuple);
4132 return -1;
4133}
Steve Dowercc16be82016-09-08 10:35:16 -07004134#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004135
4136static int
4137unicode_decode_call_errorhandler_writer(
4138 const char *errors, PyObject **errorHandler,
4139 const char *encoding, const char *reason,
4140 const char **input, const char **inend, Py_ssize_t *startinpos,
4141 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4142 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4143{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004144 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004145
4146 PyObject *restuple = NULL;
4147 PyObject *repunicode = NULL;
4148 Py_ssize_t insize;
4149 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004150 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004151 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004152 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004153 int need_to_grow = 0;
4154 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004155
4156 if (*errorHandler == NULL) {
4157 *errorHandler = PyCodec_LookupError(errors);
4158 if (*errorHandler == NULL)
4159 goto onError;
4160 }
4161
4162 make_decode_exception(exceptionObject,
4163 encoding,
4164 *input, *inend - *input,
4165 *startinpos, *endinpos,
4166 reason);
4167 if (*exceptionObject == NULL)
4168 goto onError;
4169
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004170 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004171 if (restuple == NULL)
4172 goto onError;
4173 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004174 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004175 goto onError;
4176 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004177 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004178 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004179
4180 /* Copy back the bytes variables, which might have been modified by the
4181 callback */
4182 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4183 if (!inputobj)
4184 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004185 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004186 *input = PyBytes_AS_STRING(inputobj);
4187 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004188 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004189 /* we can DECREF safely, as the exception has another reference,
4190 so the object won't go away. */
4191 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004192
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004193 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004194 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004195 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004196 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004197 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004198 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199
Victor Stinner170ca6f2013-04-18 00:25:28 +02004200 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004201 if (replen > 1) {
4202 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004203 need_to_grow = 1;
4204 }
4205 new_inptr = *input + newpos;
4206 if (*inend - new_inptr > remain) {
4207 /* We don't know the decoding algorithm here so we make the worst
4208 assumption that one byte decodes to one unicode character.
4209 If unfortunately one byte could decode to more unicode characters,
4210 the decoder may write out-of-bound then. Is it possible for the
4211 algorithms using this function? */
4212 writer->min_length += *inend - new_inptr - remain;
4213 need_to_grow = 1;
4214 }
4215 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004216 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004217 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004218 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4219 goto onError;
4220 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004221 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004222 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004223
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004225 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004226
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004227 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004228 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004229 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004230
Benjamin Peterson29060642009-01-31 22:14:21 +00004231 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004232 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004233 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004234}
4235
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004236/* --- UTF-7 Codec -------------------------------------------------------- */
4237
Antoine Pitrou244651a2009-05-04 18:56:13 +00004238/* See RFC2152 for details. We encode conservatively and decode liberally. */
4239
4240/* Three simple macros defining base-64. */
4241
4242/* Is c a base-64 character? */
4243
4244#define IS_BASE64(c) \
4245 (((c) >= 'A' && (c) <= 'Z') || \
4246 ((c) >= 'a' && (c) <= 'z') || \
4247 ((c) >= '0' && (c) <= '9') || \
4248 (c) == '+' || (c) == '/')
4249
4250/* given that c is a base-64 character, what is its base-64 value? */
4251
4252#define FROM_BASE64(c) \
4253 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4254 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4255 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4256 (c) == '+' ? 62 : 63)
4257
4258/* What is the base-64 character of the bottom 6 bits of n? */
4259
4260#define TO_BASE64(n) \
4261 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4262
4263/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4264 * decoded as itself. We are permissive on decoding; the only ASCII
4265 * byte not decoding to itself is the + which begins a base64
4266 * string. */
4267
4268#define DECODE_DIRECT(c) \
4269 ((c) <= 127 && (c) != '+')
4270
4271/* The UTF-7 encoder treats ASCII characters differently according to
4272 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4273 * the above). See RFC2152. This array identifies these different
4274 * sets:
4275 * 0 : "Set D"
4276 * alphanumeric and '(),-./:?
4277 * 1 : "Set O"
4278 * !"#$%&*;<=>@[]^_`{|}
4279 * 2 : "whitespace"
4280 * ht nl cr sp
4281 * 3 : special (must be base64 encoded)
4282 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4283 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004284
Tim Petersced69f82003-09-16 20:30:58 +00004285static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286char utf7_category[128] = {
4287/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4288 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4289/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4290 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4291/* sp ! " # $ % & ' ( ) * + , - . / */
4292 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4293/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4294 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4295/* @ A B C D E F G H I J K L M N O */
4296 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4297/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4298 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4299/* ` a b c d e f g h i j k l m n o */
4300 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4301/* p q r s t u v w x y z { | } ~ del */
4302 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004303};
4304
Antoine Pitrou244651a2009-05-04 18:56:13 +00004305/* ENCODE_DIRECT: this character should be encoded as itself. The
4306 * answer depends on whether we are encoding set O as itself, and also
4307 * on whether we are encoding whitespace as itself. RFC2152 makes it
4308 * clear that the answers to these questions vary between
4309 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004310
Antoine Pitrou244651a2009-05-04 18:56:13 +00004311#define ENCODE_DIRECT(c, directO, directWS) \
4312 ((c) < 128 && (c) > 0 && \
4313 ((utf7_category[(c)] == 0) || \
4314 (directWS && (utf7_category[(c)] == 2)) || \
4315 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316
Alexander Belopolsky40018472011-02-26 01:02:56 +00004317PyObject *
4318PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004319 Py_ssize_t size,
4320 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004321{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004322 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4323}
4324
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325/* The decoder. The only state we preserve is our read position,
4326 * i.e. how many characters we have consumed. So if we end in the
4327 * middle of a shift sequence we have to back off the read position
4328 * and the output to the beginning of the sequence, otherwise we lose
4329 * all the shift state (seen bits, number of bits seen, high
4330 * surrogate). */
4331
Alexander Belopolsky40018472011-02-26 01:02:56 +00004332PyObject *
4333PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004334 Py_ssize_t size,
4335 const char *errors,
4336 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004337{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004338 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004339 Py_ssize_t startinpos;
4340 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004342 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004343 const char *errmsg = "";
4344 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004345 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 unsigned int base64bits = 0;
4347 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004348 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004349 PyObject *errorHandler = NULL;
4350 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004351
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004352 if (size == 0) {
4353 if (consumed)
4354 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004355 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004356 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004357
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004358 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004359 _PyUnicodeWriter_Init(&writer);
4360 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004361
4362 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004363 e = s + size;
4364
4365 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004366 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004367 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004368 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004369
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 if (inShift) { /* in a base-64 section */
4371 if (IS_BASE64(ch)) { /* consume a base-64 character */
4372 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4373 base64bits += 6;
4374 s++;
4375 if (base64bits >= 16) {
4376 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004377 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378 base64bits -= 16;
4379 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004380 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (surrogate) {
4382 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004383 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4384 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004385 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004386 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004387 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004388 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389 }
4390 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004391 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004392 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004393 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004394 }
4395 }
Victor Stinner551ac952011-11-29 22:58:13 +01004396 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397 /* first surrogate */
4398 surrogate = outCh;
4399 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004400 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004401 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004402 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 }
4404 }
4405 }
4406 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 if (base64bits > 0) { /* left-over bits */
4409 if (base64bits >= 6) {
4410 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004411 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 errmsg = "partial character in shift sequence";
4413 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 else {
4416 /* Some bits remain; they should be zero */
4417 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004418 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 errmsg = "non-zero padding bits in shift sequence";
4420 goto utf7Error;
4421 }
4422 }
4423 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004424 if (surrogate && DECODE_DIRECT(ch)) {
4425 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4426 goto onError;
4427 }
4428 surrogate = 0;
4429 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430 /* '-' is absorbed; other terminating
4431 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004432 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004434 }
4435 }
4436 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004437 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 s++; /* consume '+' */
4439 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004440 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004441 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004442 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004444 else if (s < e && !IS_BASE64(*s)) {
4445 s++;
4446 errmsg = "ill-formed sequence";
4447 goto utf7Error;
4448 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004451 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004452 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004454 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004455 }
4456 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004458 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004459 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004460 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004461 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 else {
4463 startinpos = s-starts;
4464 s++;
4465 errmsg = "unexpected special character";
4466 goto utf7Error;
4467 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004468 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004469utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004470 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004471 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 errors, &errorHandler,
4473 "utf7", errmsg,
4474 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004475 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004476 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477 }
4478
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 /* end of string */
4480
4481 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4482 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004483 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004484 if (surrogate ||
4485 (base64bits >= 6) ||
4486 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004488 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489 errors, &errorHandler,
4490 "utf7", "unterminated shift sequence",
4491 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004492 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004493 goto onError;
4494 if (s < e)
4495 goto restart;
4496 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498
4499 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004500 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004501 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004502 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004503 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004504 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004505 writer.kind, writer.data, shiftOutStart);
4506 Py_XDECREF(errorHandler);
4507 Py_XDECREF(exc);
4508 _PyUnicodeWriter_Dealloc(&writer);
4509 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004510 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004511 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 }
4513 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004514 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004515 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004516 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004518 Py_XDECREF(errorHandler);
4519 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004520 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004521
Benjamin Peterson29060642009-01-31 22:14:21 +00004522 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004523 Py_XDECREF(errorHandler);
4524 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004525 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526 return NULL;
4527}
4528
4529
Alexander Belopolsky40018472011-02-26 01:02:56 +00004530PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004531_PyUnicode_EncodeUTF7(PyObject *str,
4532 int base64SetO,
4533 int base64WhiteSpace,
4534 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004536 int kind;
4537 void *data;
4538 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004539 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004541 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 unsigned int base64bits = 0;
4543 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 char * out;
4545 char * start;
4546
Benjamin Petersonbac79492012-01-14 13:34:47 -05004547 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004548 return NULL;
4549 kind = PyUnicode_KIND(str);
4550 data = PyUnicode_DATA(str);
4551 len = PyUnicode_GET_LENGTH(str);
4552
4553 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004556 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004557 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004558 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004559 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004560 if (v == NULL)
4561 return NULL;
4562
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004563 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004564 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004565 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004566
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567 if (inShift) {
4568 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4569 /* shifting out */
4570 if (base64bits) { /* output remaining bits */
4571 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4572 base64buffer = 0;
4573 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004574 }
4575 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 /* Characters not in the BASE64 set implicitly unshift the sequence
4577 so no '-' is required, except if the character is itself a '-' */
4578 if (IS_BASE64(ch) || ch == '-') {
4579 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004580 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 *out++ = (char) ch;
4582 }
4583 else {
4584 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004585 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004586 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 else { /* not in a shift sequence */
4588 if (ch == '+') {
4589 *out++ = '+';
4590 *out++ = '-';
4591 }
4592 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4593 *out++ = (char) ch;
4594 }
4595 else {
4596 *out++ = '+';
4597 inShift = 1;
4598 goto encode_char;
4599 }
4600 }
4601 continue;
4602encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004603 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004604 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004605
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606 /* code first surrogate */
4607 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004608 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004609 while (base64bits >= 6) {
4610 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4611 base64bits -= 6;
4612 }
4613 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004614 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004615 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004616 base64bits += 16;
4617 base64buffer = (base64buffer << 16) | ch;
4618 while (base64bits >= 6) {
4619 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4620 base64bits -= 6;
4621 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004622 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004623 if (base64bits)
4624 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4625 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004626 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004627 if (_PyBytes_Resize(&v, out - start) < 0)
4628 return NULL;
4629 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004630}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004631PyObject *
4632PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4633 Py_ssize_t size,
4634 int base64SetO,
4635 int base64WhiteSpace,
4636 const char *errors)
4637{
4638 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004639 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004640 if (tmp == NULL)
4641 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004642 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004643 base64WhiteSpace, errors);
4644 Py_DECREF(tmp);
4645 return result;
4646}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004647
Antoine Pitrou244651a2009-05-04 18:56:13 +00004648#undef IS_BASE64
4649#undef FROM_BASE64
4650#undef TO_BASE64
4651#undef DECODE_DIRECT
4652#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004653
Guido van Rossumd57fd912000-03-10 22:53:23 +00004654/* --- UTF-8 Codec -------------------------------------------------------- */
4655
Alexander Belopolsky40018472011-02-26 01:02:56 +00004656PyObject *
4657PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004658 Py_ssize_t size,
4659 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004660{
Walter Dörwald69652032004-09-07 20:24:22 +00004661 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4662}
4663
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664#include "stringlib/asciilib.h"
4665#include "stringlib/codecs.h"
4666#include "stringlib/undef.h"
4667
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004668#include "stringlib/ucs1lib.h"
4669#include "stringlib/codecs.h"
4670#include "stringlib/undef.h"
4671
4672#include "stringlib/ucs2lib.h"
4673#include "stringlib/codecs.h"
4674#include "stringlib/undef.h"
4675
4676#include "stringlib/ucs4lib.h"
4677#include "stringlib/codecs.h"
4678#include "stringlib/undef.h"
4679
Antoine Pitrouab868312009-01-10 15:40:25 +00004680/* Mask to quickly check whether a C 'long' contains a
4681 non-ASCII, UTF8-encoded char. */
4682#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004683# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004684#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004685# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004686#else
4687# error C 'long' size should be either 4 or 8!
4688#endif
4689
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690static Py_ssize_t
4691ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004692{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004693 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004694 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004695
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004696 /*
4697 * Issue #17237: m68k is a bit different from most architectures in
4698 * that objects do not use "natural alignment" - for example, int and
4699 * long are only aligned at 2-byte boundaries. Therefore the assert()
4700 * won't work; also, tests have shown that skipping the "optimised
4701 * version" will even speed up m68k.
4702 */
4703#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004705 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4706 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004707 /* Fast path, see in STRINGLIB(utf8_decode) for
4708 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004709 /* Help allocation */
4710 const char *_p = p;
4711 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 while (_p < aligned_end) {
4713 unsigned long value = *(const unsigned long *) _p;
4714 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004715 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004716 *((unsigned long *)q) = value;
4717 _p += SIZEOF_LONG;
4718 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004719 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004720 p = _p;
4721 while (p < end) {
4722 if ((unsigned char)*p & 0x80)
4723 break;
4724 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004725 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004727 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004728#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004729#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 while (p < end) {
4731 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4732 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004733 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004734 /* Help allocation */
4735 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004736 while (_p < aligned_end) {
4737 unsigned long value = *(unsigned long *) _p;
4738 if (value & ASCII_CHAR_MASK)
4739 break;
4740 _p += SIZEOF_LONG;
4741 }
4742 p = _p;
4743 if (_p == end)
4744 break;
4745 }
4746 if ((unsigned char)*p & 0x80)
4747 break;
4748 ++p;
4749 }
4750 memcpy(dest, start, p - start);
4751 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004752}
Antoine Pitrouab868312009-01-10 15:40:25 +00004753
Victor Stinner785938e2011-12-11 20:09:03 +01004754PyObject *
4755PyUnicode_DecodeUTF8Stateful(const char *s,
4756 Py_ssize_t size,
4757 const char *errors,
4758 Py_ssize_t *consumed)
4759{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004760 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004761 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763
4764 Py_ssize_t startinpos;
4765 Py_ssize_t endinpos;
4766 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004767 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004769 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004770
4771 if (size == 0) {
4772 if (consumed)
4773 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004774 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004775 }
4776
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4778 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004779 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004780 *consumed = 1;
4781 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004782 }
4783
Victor Stinner8f674cc2013-04-17 23:02:17 +02004784 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004785 writer.min_length = size;
4786 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004787 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004788
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004789 writer.pos = ascii_decode(s, end, writer.data);
4790 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791 while (s < end) {
4792 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004793 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004794
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004796 if (PyUnicode_IS_ASCII(writer.buffer))
4797 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004799 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004801 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004802 } else {
4803 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004804 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004805 }
4806
4807 switch (ch) {
4808 case 0:
4809 if (s == end || consumed)
4810 goto End;
4811 errmsg = "unexpected end of data";
4812 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004813 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814 break;
4815 case 1:
4816 errmsg = "invalid start byte";
4817 startinpos = s - starts;
4818 endinpos = startinpos + 1;
4819 break;
4820 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004821 case 3:
4822 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823 errmsg = "invalid continuation byte";
4824 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004825 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826 break;
4827 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004828 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004829 goto onError;
4830 continue;
4831 }
4832
Victor Stinner1d65d912015-10-05 13:43:50 +02004833 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02004834 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02004835
4836 switch (error_handler) {
4837 case _Py_ERROR_IGNORE:
4838 s += (endinpos - startinpos);
4839 break;
4840
4841 case _Py_ERROR_REPLACE:
4842 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4843 goto onError;
4844 s += (endinpos - startinpos);
4845 break;
4846
4847 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004848 {
4849 Py_ssize_t i;
4850
Victor Stinner1d65d912015-10-05 13:43:50 +02004851 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4852 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004853 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004854 ch = (Py_UCS4)(unsigned char)(starts[i]);
4855 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4856 ch + 0xdc00);
4857 writer.pos++;
4858 }
4859 s += (endinpos - startinpos);
4860 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004861 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004862
4863 default:
4864 if (unicode_decode_call_errorhandler_writer(
4865 errors, &error_handler_obj,
4866 "utf-8", errmsg,
4867 &starts, &end, &startinpos, &endinpos, &exc, &s,
4868 &writer))
4869 goto onError;
4870 }
Victor Stinner785938e2011-12-11 20:09:03 +01004871 }
4872
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004873End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004874 if (consumed)
4875 *consumed = s - starts;
4876
Victor Stinner1d65d912015-10-05 13:43:50 +02004877 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004878 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004879 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004880
4881onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004882 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004883 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004884 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004885 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004886}
4887
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004888
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004889/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4890 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004891
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004892 On success, write a pointer to a newly allocated wide character string into
4893 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4894 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004895
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004896 On memory allocation failure, return -1.
4897
4898 On decoding error (if surrogateescape is zero), return -2. If wlen is
4899 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4900 is not NULL, write the decoding error message into *reason. */
4901int
4902_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02004903 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004904{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004905 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004906 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004907 wchar_t *unicode;
4908 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004909
Victor Stinner3d4226a2018-08-29 22:21:32 +02004910 int surrogateescape = 0;
4911 int surrogatepass = 0;
4912 switch (errors)
4913 {
4914 case _Py_ERROR_STRICT:
4915 break;
4916 case _Py_ERROR_SURROGATEESCAPE:
4917 surrogateescape = 1;
4918 break;
4919 case _Py_ERROR_SURROGATEPASS:
4920 surrogatepass = 1;
4921 break;
4922 default:
4923 return -3;
4924 }
4925
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004926 /* Note: size will always be longer than the resulting Unicode
4927 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004928 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004929 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004930 }
4931
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004932 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004933 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004934 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004935 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004936
4937 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004938 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004939 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004940 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004941 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004943 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004944#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004946#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004947 if (ch > 0xFF) {
4948#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004949 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004950#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004951 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004952 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004953 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4954 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4955#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004956 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004957 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02004958 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004960 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02004961
4962 if (surrogateescape) {
4963 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4964 }
4965 else {
4966 /* Is it a valid three-byte code? */
4967 if (surrogatepass
4968 && (e - s) >= 3
4969 && (s[0] & 0xf0) == 0xe0
4970 && (s[1] & 0xc0) == 0x80
4971 && (s[2] & 0xc0) == 0x80)
4972 {
4973 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4974 s += 3;
4975 unicode[outpos++] = ch;
4976 }
4977 else {
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 }
4998 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005000 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005001 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005002 if (wlen) {
5003 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005004 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005005 *wstr = unicode;
5006 return 0;
5007}
5008
5009wchar_t*
5010_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5011{
5012 wchar_t *wstr;
5013 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5014 if (res != 0) {
5015 return NULL;
5016 }
5017 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005018}
5019
Antoine Pitrouab868312009-01-10 15:40:25 +00005020
Victor Stinnere47e6982017-12-21 15:45:16 +01005021/* UTF-8 encoder using the surrogateescape error handler .
5022
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005023 On success, return 0 and write the newly allocated character string (use
5024 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005025
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005026 On encoding failure, return -2 and write the position of the invalid
5027 surrogate character into *error_pos (if error_pos is set) and the decoding
5028 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005029
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005030 On memory allocation failure, return -1. */
5031int
5032_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005033 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005034{
5035 const Py_ssize_t max_char_size = 4;
5036 Py_ssize_t len = wcslen(text);
5037
5038 assert(len >= 0);
5039
Victor Stinner3d4226a2018-08-29 22:21:32 +02005040 int surrogateescape = 0;
5041 int surrogatepass = 0;
5042 switch (errors)
5043 {
5044 case _Py_ERROR_STRICT:
5045 break;
5046 case _Py_ERROR_SURROGATEESCAPE:
5047 surrogateescape = 1;
5048 break;
5049 case _Py_ERROR_SURROGATEPASS:
5050 surrogatepass = 1;
5051 break;
5052 default:
5053 return -3;
5054 }
5055
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005056 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5057 return -1;
5058 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005059 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005060 if (raw_malloc) {
5061 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005062 }
5063 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005064 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005065 }
5066 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005067 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005068 }
5069
5070 char *p = bytes;
5071 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005072 for (i = 0; i < len; ) {
5073 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005074 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005075 i++;
5076#if Py_UNICODE_SIZE == 2
5077 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5078 && i < len
5079 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5080 {
5081 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5082 i++;
5083 }
5084#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005085
5086 if (ch < 0x80) {
5087 /* Encode ASCII */
5088 *p++ = (char) ch;
5089
5090 }
5091 else if (ch < 0x0800) {
5092 /* Encode Latin-1 */
5093 *p++ = (char)(0xc0 | (ch >> 6));
5094 *p++ = (char)(0x80 | (ch & 0x3f));
5095 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005096 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005097 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005098 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005099 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005100 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005101 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005102 if (reason != NULL) {
5103 *reason = "encoding error";
5104 }
5105 if (raw_malloc) {
5106 PyMem_RawFree(bytes);
5107 }
5108 else {
5109 PyMem_Free(bytes);
5110 }
5111 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005112 }
5113 *p++ = (char)(ch & 0xff);
5114 }
5115 else if (ch < 0x10000) {
5116 *p++ = (char)(0xe0 | (ch >> 12));
5117 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5118 *p++ = (char)(0x80 | (ch & 0x3f));
5119 }
5120 else { /* ch >= 0x10000 */
5121 assert(ch <= MAX_UNICODE);
5122 /* Encode UCS4 Unicode ordinals */
5123 *p++ = (char)(0xf0 | (ch >> 18));
5124 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5125 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5126 *p++ = (char)(0x80 | (ch & 0x3f));
5127 }
5128 }
5129 *p++ = '\0';
5130
5131 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005132 char *bytes2;
5133 if (raw_malloc) {
5134 bytes2 = PyMem_RawRealloc(bytes, final_size);
5135 }
5136 else {
5137 bytes2 = PyMem_Realloc(bytes, final_size);
5138 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005139 if (bytes2 == NULL) {
5140 if (error_pos != NULL) {
5141 *error_pos = (size_t)-1;
5142 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005143 if (raw_malloc) {
5144 PyMem_RawFree(bytes);
5145 }
5146 else {
5147 PyMem_Free(bytes);
5148 }
5149 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005150 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005151 *str = bytes2;
5152 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005153}
5154
5155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005156/* Primary internal function which creates utf8 encoded bytes objects.
5157
5158 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005159 and allocate exactly as much space needed at the end. Else allocate the
5160 maximum possible needed (4 result bytes per Unicode character), and return
5161 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005162*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005163PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005164_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005165{
Victor Stinner6099a032011-12-18 14:22:26 +01005166 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005167 void *data;
5168 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005170 if (!PyUnicode_Check(unicode)) {
5171 PyErr_BadArgument();
5172 return NULL;
5173 }
5174
5175 if (PyUnicode_READY(unicode) == -1)
5176 return NULL;
5177
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005178 if (PyUnicode_UTF8(unicode))
5179 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5180 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005181
5182 kind = PyUnicode_KIND(unicode);
5183 data = PyUnicode_DATA(unicode);
5184 size = PyUnicode_GET_LENGTH(unicode);
5185
Benjamin Petersonead6b532011-12-20 17:23:42 -06005186 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005187 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005188 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005189 case PyUnicode_1BYTE_KIND:
5190 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5191 assert(!PyUnicode_IS_ASCII(unicode));
5192 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5193 case PyUnicode_2BYTE_KIND:
5194 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5195 case PyUnicode_4BYTE_KIND:
5196 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005197 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198}
5199
Alexander Belopolsky40018472011-02-26 01:02:56 +00005200PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005201PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5202 Py_ssize_t size,
5203 const char *errors)
5204{
5205 PyObject *v, *unicode;
5206
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005207 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005208 if (unicode == NULL)
5209 return NULL;
5210 v = _PyUnicode_AsUTF8String(unicode, errors);
5211 Py_DECREF(unicode);
5212 return v;
5213}
5214
5215PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005216PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005217{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005218 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005219}
5220
Walter Dörwald41980ca2007-08-16 21:55:45 +00005221/* --- UTF-32 Codec ------------------------------------------------------- */
5222
5223PyObject *
5224PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005225 Py_ssize_t size,
5226 const char *errors,
5227 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005228{
5229 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5230}
5231
5232PyObject *
5233PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005234 Py_ssize_t size,
5235 const char *errors,
5236 int *byteorder,
5237 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238{
5239 const char *starts = s;
5240 Py_ssize_t startinpos;
5241 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005242 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005243 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005244 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005245 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005246 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005247 PyObject *errorHandler = NULL;
5248 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005249
Walter Dörwald41980ca2007-08-16 21:55:45 +00005250 q = (unsigned char *)s;
5251 e = q + size;
5252
5253 if (byteorder)
5254 bo = *byteorder;
5255
5256 /* Check for BOM marks (U+FEFF) in the input and adjust current
5257 byte order setting accordingly. In native mode, the leading BOM
5258 mark is skipped, in all other modes, it is copied to the output
5259 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005260 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005261 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005262 if (bom == 0x0000FEFF) {
5263 bo = -1;
5264 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005265 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005266 else if (bom == 0xFFFE0000) {
5267 bo = 1;
5268 q += 4;
5269 }
5270 if (byteorder)
5271 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005272 }
5273
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 if (q == e) {
5275 if (consumed)
5276 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005277 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005278 }
5279
Victor Stinnere64322e2012-10-30 23:12:47 +01005280#ifdef WORDS_BIGENDIAN
5281 le = bo < 0;
5282#else
5283 le = bo <= 0;
5284#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005285 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005286
Victor Stinner8f674cc2013-04-17 23:02:17 +02005287 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005288 writer.min_length = (e - q + 3) / 4;
5289 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005290 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005291
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 while (1) {
5293 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005294 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005295
Victor Stinnere64322e2012-10-30 23:12:47 +01005296 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005297 enum PyUnicode_Kind kind = writer.kind;
5298 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005299 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005300 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005301 if (le) {
5302 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005303 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 if (ch > maxch)
5305 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005306 if (kind != PyUnicode_1BYTE_KIND &&
5307 Py_UNICODE_IS_SURROGATE(ch))
5308 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005309 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005310 q += 4;
5311 } while (q <= last);
5312 }
5313 else {
5314 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005315 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 if (ch > maxch)
5317 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005318 if (kind != PyUnicode_1BYTE_KIND &&
5319 Py_UNICODE_IS_SURROGATE(ch))
5320 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005321 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005322 q += 4;
5323 } while (q <= last);
5324 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005325 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005326 }
5327
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005328 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005329 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005330 startinpos = ((const char *)q) - starts;
5331 endinpos = startinpos + 4;
5332 }
5333 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005334 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005335 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005336 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005338 startinpos = ((const char *)q) - starts;
5339 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005341 else {
5342 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005343 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005344 goto onError;
5345 q += 4;
5346 continue;
5347 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005348 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005349 startinpos = ((const char *)q) - starts;
5350 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005352
5353 /* The remaining input chars are ignored if the callback
5354 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005355 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005357 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005359 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005360 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005361 }
5362
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005365
Walter Dörwald41980ca2007-08-16 21:55:45 +00005366 Py_XDECREF(errorHandler);
5367 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005368 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005369
Benjamin Peterson29060642009-01-31 22:14:21 +00005370 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005371 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005372 Py_XDECREF(errorHandler);
5373 Py_XDECREF(exc);
5374 return NULL;
5375}
5376
5377PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005378_PyUnicode_EncodeUTF32(PyObject *str,
5379 const char *errors,
5380 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005381{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005382 enum PyUnicode_Kind kind;
5383 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005384 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005385 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005386 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005387#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005388 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005389#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005391#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005392 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005393 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005394 PyObject *errorHandler = NULL;
5395 PyObject *exc = NULL;
5396 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005397
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005398 if (!PyUnicode_Check(str)) {
5399 PyErr_BadArgument();
5400 return NULL;
5401 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005402 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005403 return NULL;
5404 kind = PyUnicode_KIND(str);
5405 data = PyUnicode_DATA(str);
5406 len = PyUnicode_GET_LENGTH(str);
5407
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005408 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005409 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005410 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005411 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005412 if (v == NULL)
5413 return NULL;
5414
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005415 /* output buffer is 4-bytes aligned */
5416 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005417 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005418 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005419 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005420 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005421 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005422
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005423 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005424 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005426 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 else
5428 encoding = "utf-32";
5429
5430 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005431 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5432 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005433 }
5434
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005435 pos = 0;
5436 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005437 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005438
5439 if (kind == PyUnicode_2BYTE_KIND) {
5440 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5441 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005442 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005443 else {
5444 assert(kind == PyUnicode_4BYTE_KIND);
5445 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5446 &out, native_ordering);
5447 }
5448 if (pos == len)
5449 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005450
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005451 rep = unicode_encode_call_errorhandler(
5452 errors, &errorHandler,
5453 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005454 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005455 if (!rep)
5456 goto error;
5457
5458 if (PyBytes_Check(rep)) {
5459 repsize = PyBytes_GET_SIZE(rep);
5460 if (repsize & 3) {
5461 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005462 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 "surrogates not allowed");
5464 goto error;
5465 }
5466 moreunits = repsize / 4;
5467 }
5468 else {
5469 assert(PyUnicode_Check(rep));
5470 if (PyUnicode_READY(rep) < 0)
5471 goto error;
5472 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5473 if (!PyUnicode_IS_ASCII(rep)) {
5474 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005475 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005476 "surrogates not allowed");
5477 goto error;
5478 }
5479 }
5480
5481 /* four bytes are reserved for each surrogate */
5482 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005483 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005484 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005485 /* integer overflow */
5486 PyErr_NoMemory();
5487 goto error;
5488 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005489 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005490 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005491 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005492 }
5493
5494 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005495 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005496 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005497 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005498 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005499 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5500 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005501 }
5502
5503 Py_CLEAR(rep);
5504 }
5505
5506 /* Cut back to size actually needed. This is necessary for, for example,
5507 encoding of a string containing isolated surrogates and the 'ignore'
5508 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005509 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005510 if (nsize != PyBytes_GET_SIZE(v))
5511 _PyBytes_Resize(&v, nsize);
5512 Py_XDECREF(errorHandler);
5513 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005514 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005515 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005516 error:
5517 Py_XDECREF(rep);
5518 Py_XDECREF(errorHandler);
5519 Py_XDECREF(exc);
5520 Py_XDECREF(v);
5521 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005522}
5523
Alexander Belopolsky40018472011-02-26 01:02:56 +00005524PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005525PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5526 Py_ssize_t size,
5527 const char *errors,
5528 int byteorder)
5529{
5530 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005531 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005532 if (tmp == NULL)
5533 return NULL;
5534 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5535 Py_DECREF(tmp);
5536 return result;
5537}
5538
5539PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005540PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005541{
Victor Stinnerb960b342011-11-20 19:12:52 +01005542 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005543}
5544
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545/* --- UTF-16 Codec ------------------------------------------------------- */
5546
Tim Peters772747b2001-08-09 22:21:55 +00005547PyObject *
5548PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005549 Py_ssize_t size,
5550 const char *errors,
5551 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005552{
Walter Dörwald69652032004-09-07 20:24:22 +00005553 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5554}
5555
5556PyObject *
5557PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005558 Py_ssize_t size,
5559 const char *errors,
5560 int *byteorder,
5561 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005562{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005563 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005564 Py_ssize_t startinpos;
5565 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005566 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005567 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005568 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005569 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005570 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005571 PyObject *errorHandler = NULL;
5572 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005573 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574
Tim Peters772747b2001-08-09 22:21:55 +00005575 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005576 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577
5578 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005579 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005580
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005581 /* Check for BOM marks (U+FEFF) in the input and adjust current
5582 byte order setting accordingly. In native mode, the leading BOM
5583 mark is skipped, in all other modes, it is copied to the output
5584 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 if (bo == 0 && size >= 2) {
5586 const Py_UCS4 bom = (q[1] << 8) | q[0];
5587 if (bom == 0xFEFF) {
5588 q += 2;
5589 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591 else if (bom == 0xFFFE) {
5592 q += 2;
5593 bo = 1;
5594 }
5595 if (byteorder)
5596 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005597 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005598
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 if (q == e) {
5600 if (consumed)
5601 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005602 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005603 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604
Christian Heimes743e0cd2012-10-17 23:52:17 +02005605#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005607 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005608#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005609 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005610 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005611#endif
Tim Peters772747b2001-08-09 22:21:55 +00005612
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005614 character count normally. Error handler will take care of
5615 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005616 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005617 writer.min_length = (e - q + 1) / 2;
5618 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005619 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005620
Antoine Pitrou63065d72012-05-15 23:48:04 +02005621 while (1) {
5622 Py_UCS4 ch = 0;
5623 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005624 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005625 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005626 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005627 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005628 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005629 native_ordering);
5630 else
5631 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005632 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005633 native_ordering);
5634 } else if (kind == PyUnicode_2BYTE_KIND) {
5635 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005636 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005637 native_ordering);
5638 } else {
5639 assert(kind == PyUnicode_4BYTE_KIND);
5640 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005641 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005642 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005643 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005644 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005645
Antoine Pitrou63065d72012-05-15 23:48:04 +02005646 switch (ch)
5647 {
5648 case 0:
5649 /* remaining byte at the end? (size should be even) */
5650 if (q == e || consumed)
5651 goto End;
5652 errmsg = "truncated data";
5653 startinpos = ((const char *)q) - starts;
5654 endinpos = ((const char *)e) - starts;
5655 break;
5656 /* The remaining input chars are ignored if the callback
5657 chooses to skip the input */
5658 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005659 q -= 2;
5660 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005661 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005662 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005663 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005664 endinpos = ((const char *)e) - starts;
5665 break;
5666 case 2:
5667 errmsg = "illegal encoding";
5668 startinpos = ((const char *)q) - 2 - starts;
5669 endinpos = startinpos + 2;
5670 break;
5671 case 3:
5672 errmsg = "illegal UTF-16 surrogate";
5673 startinpos = ((const char *)q) - 4 - starts;
5674 endinpos = startinpos + 2;
5675 break;
5676 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005677 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005678 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005679 continue;
5680 }
5681
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005682 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005683 errors,
5684 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005685 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005686 &starts,
5687 (const char **)&e,
5688 &startinpos,
5689 &endinpos,
5690 &exc,
5691 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005692 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 }
5695
Antoine Pitrou63065d72012-05-15 23:48:04 +02005696End:
Walter Dörwald69652032004-09-07 20:24:22 +00005697 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005698 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005699
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005700 Py_XDECREF(errorHandler);
5701 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005702 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703
Benjamin Peterson29060642009-01-31 22:14:21 +00005704 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005705 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005706 Py_XDECREF(errorHandler);
5707 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005708 return NULL;
5709}
5710
Tim Peters772747b2001-08-09 22:21:55 +00005711PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005712_PyUnicode_EncodeUTF16(PyObject *str,
5713 const char *errors,
5714 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005715{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005716 enum PyUnicode_Kind kind;
5717 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005718 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005719 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005720 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005721 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005722#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005723 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005724#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005725 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005726#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005727 const char *encoding;
5728 Py_ssize_t nsize, pos;
5729 PyObject *errorHandler = NULL;
5730 PyObject *exc = NULL;
5731 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005732
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005733 if (!PyUnicode_Check(str)) {
5734 PyErr_BadArgument();
5735 return NULL;
5736 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005737 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005738 return NULL;
5739 kind = PyUnicode_KIND(str);
5740 data = PyUnicode_DATA(str);
5741 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005742
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005743 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005744 if (kind == PyUnicode_4BYTE_KIND) {
5745 const Py_UCS4 *in = (const Py_UCS4 *)data;
5746 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005747 while (in < end) {
5748 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005749 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005750 }
5751 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005752 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005753 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005755 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005756 nsize = len + pairs + (byteorder == 0);
5757 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005758 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005760 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005762 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005763 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005764 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005765 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005766 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005767 }
5768 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005769 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005770 }
Tim Peters772747b2001-08-09 22:21:55 +00005771
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005772 if (kind == PyUnicode_1BYTE_KIND) {
5773 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5774 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005775 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005776
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005777 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005778 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005779 }
5780 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005781 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005782 }
5783 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005784 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005785 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005786
5787 pos = 0;
5788 while (pos < len) {
5789 Py_ssize_t repsize, moreunits;
5790
5791 if (kind == PyUnicode_2BYTE_KIND) {
5792 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5793 &out, native_ordering);
5794 }
5795 else {
5796 assert(kind == PyUnicode_4BYTE_KIND);
5797 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5798 &out, native_ordering);
5799 }
5800 if (pos == len)
5801 break;
5802
5803 rep = unicode_encode_call_errorhandler(
5804 errors, &errorHandler,
5805 encoding, "surrogates not allowed",
5806 str, &exc, pos, pos + 1, &pos);
5807 if (!rep)
5808 goto error;
5809
5810 if (PyBytes_Check(rep)) {
5811 repsize = PyBytes_GET_SIZE(rep);
5812 if (repsize & 1) {
5813 raise_encode_exception(&exc, encoding,
5814 str, pos - 1, pos,
5815 "surrogates not allowed");
5816 goto error;
5817 }
5818 moreunits = repsize / 2;
5819 }
5820 else {
5821 assert(PyUnicode_Check(rep));
5822 if (PyUnicode_READY(rep) < 0)
5823 goto error;
5824 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5825 if (!PyUnicode_IS_ASCII(rep)) {
5826 raise_encode_exception(&exc, encoding,
5827 str, pos - 1, pos,
5828 "surrogates not allowed");
5829 goto error;
5830 }
5831 }
5832
5833 /* two bytes are reserved for each surrogate */
5834 if (moreunits > 1) {
5835 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005836 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005837 /* integer overflow */
5838 PyErr_NoMemory();
5839 goto error;
5840 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005841 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005842 goto error;
5843 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5844 }
5845
5846 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005847 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005848 out += moreunits;
5849 } else /* rep is unicode */ {
5850 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5851 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5852 &out, native_ordering);
5853 }
5854
5855 Py_CLEAR(rep);
5856 }
5857
5858 /* Cut back to size actually needed. This is necessary for, for example,
5859 encoding of a string containing isolated surrogates and the 'ignore' handler
5860 is used. */
5861 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5862 if (nsize != PyBytes_GET_SIZE(v))
5863 _PyBytes_Resize(&v, nsize);
5864 Py_XDECREF(errorHandler);
5865 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005866 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005867 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005868 error:
5869 Py_XDECREF(rep);
5870 Py_XDECREF(errorHandler);
5871 Py_XDECREF(exc);
5872 Py_XDECREF(v);
5873 return NULL;
5874#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875}
5876
Alexander Belopolsky40018472011-02-26 01:02:56 +00005877PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005878PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5879 Py_ssize_t size,
5880 const char *errors,
5881 int byteorder)
5882{
5883 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005884 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005885 if (tmp == NULL)
5886 return NULL;
5887 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5888 Py_DECREF(tmp);
5889 return result;
5890}
5891
5892PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005893PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005895 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896}
5897
5898/* --- Unicode Escape Codec ----------------------------------------------- */
5899
Fredrik Lundh06d12682001-01-24 07:59:11 +00005900static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005901
Alexander Belopolsky40018472011-02-26 01:02:56 +00005902PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005903_PyUnicode_DecodeUnicodeEscape(const char *s,
5904 Py_ssize_t size,
5905 const char *errors,
5906 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005909 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 PyObject *errorHandler = NULL;
5912 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005913
Eric V. Smith42454af2016-10-31 09:22:08 -04005914 // so we can remember if we've seen an invalid escape char or not
5915 *first_invalid_escape = NULL;
5916
Victor Stinner62ec3312016-09-06 17:04:34 -07005917 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005918 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005919 }
5920 /* Escaped strings will always be longer than the resulting
5921 Unicode string, so we start with size here and then reduce the
5922 length after conversion to the true value.
5923 (but if the error callback returns a long replacement string
5924 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005925 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005926 writer.min_length = size;
5927 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5928 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005929 }
5930
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 end = s + size;
5932 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005933 unsigned char c = (unsigned char) *s++;
5934 Py_UCS4 ch;
5935 int count;
5936 Py_ssize_t startinpos;
5937 Py_ssize_t endinpos;
5938 const char *message;
5939
5940#define WRITE_ASCII_CHAR(ch) \
5941 do { \
5942 assert(ch <= 127); \
5943 assert(writer.pos < writer.size); \
5944 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5945 } while(0)
5946
5947#define WRITE_CHAR(ch) \
5948 do { \
5949 if (ch <= writer.maxchar) { \
5950 assert(writer.pos < writer.size); \
5951 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5952 } \
5953 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5954 goto onError; \
5955 } \
5956 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957
5958 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005959 if (c != '\\') {
5960 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961 continue;
5962 }
5963
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005965 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005966 if (s >= end) {
5967 message = "\\ at end of string";
5968 goto error;
5969 }
5970 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005971
Victor Stinner62ec3312016-09-06 17:04:34 -07005972 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005973 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005976 case '\n': continue;
5977 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5978 case '\'': WRITE_ASCII_CHAR('\''); continue;
5979 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5980 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005981 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005982 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5983 case 't': WRITE_ASCII_CHAR('\t'); continue;
5984 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5985 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005986 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005987 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005988 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005989 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 case '0': case '1': case '2': case '3':
5993 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005994 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005995 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005996 ch = (ch<<3) + *s++ - '0';
5997 if (s < end && '0' <= *s && *s <= '7') {
5998 ch = (ch<<3) + *s++ - '0';
5999 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 WRITE_CHAR(ch);
6002 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 /* hex escapes */
6005 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006007 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006008 message = "truncated \\xXX escape";
6009 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006013 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006014 message = "truncated \\uXXXX escape";
6015 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016
Benjamin Peterson29060642009-01-31 22:14:21 +00006017 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006018 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006019 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006020 message = "truncated \\UXXXXXXXX escape";
6021 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006022 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006023 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006024 ch <<= 4;
6025 if (c >= '0' && c <= '9') {
6026 ch += c - '0';
6027 }
6028 else if (c >= 'a' && c <= 'f') {
6029 ch += c - ('a' - 10);
6030 }
6031 else if (c >= 'A' && c <= 'F') {
6032 ch += c - ('A' - 10);
6033 }
6034 else {
6035 break;
6036 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006037 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006039 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006040 }
6041
6042 /* when we get here, ch is a 32-bit unicode character */
6043 if (ch > MAX_UNICODE) {
6044 message = "illegal Unicode character";
6045 goto error;
6046 }
6047
6048 WRITE_CHAR(ch);
6049 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006050
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006052 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 if (ucnhash_CAPI == NULL) {
6054 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006055 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6056 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006057 if (ucnhash_CAPI == NULL) {
6058 PyErr_SetString(
6059 PyExc_UnicodeError,
6060 "\\N escapes not supported (can't load unicodedata module)"
6061 );
6062 goto onError;
6063 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006064 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006065
6066 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006067 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006068 const char *start = ++s;
6069 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006070 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006072 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 namelen = s - start;
6074 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006075 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006076 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006077 ch = 0xffffffff; /* in case 'getcode' messes up */
6078 if (namelen <= INT_MAX &&
6079 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6080 &ch, 0)) {
6081 assert(ch <= MAX_UNICODE);
6082 WRITE_CHAR(ch);
6083 continue;
6084 }
6085 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006086 }
6087 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006088 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006089
6090 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006091 if (*first_invalid_escape == NULL) {
6092 *first_invalid_escape = s-1; /* Back up one char, since we've
6093 already incremented s. */
6094 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006095 WRITE_ASCII_CHAR('\\');
6096 WRITE_CHAR(c);
6097 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006099
6100 error:
6101 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006102 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006103 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006104 errors, &errorHandler,
6105 "unicodeescape", message,
6106 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006107 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006108 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006109 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006110 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006111
6112#undef WRITE_ASCII_CHAR
6113#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006115
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006116 Py_XDECREF(errorHandler);
6117 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006118 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006119
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006121 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006122 Py_XDECREF(errorHandler);
6123 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006124 return NULL;
6125}
6126
Eric V. Smith42454af2016-10-31 09:22:08 -04006127PyObject *
6128PyUnicode_DecodeUnicodeEscape(const char *s,
6129 Py_ssize_t size,
6130 const char *errors)
6131{
6132 const char *first_invalid_escape;
6133 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6134 &first_invalid_escape);
6135 if (result == NULL)
6136 return NULL;
6137 if (first_invalid_escape != NULL) {
6138 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6139 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006140 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006141 Py_DECREF(result);
6142 return NULL;
6143 }
6144 }
6145 return result;
6146}
6147
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006148/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149
Alexander Belopolsky40018472011-02-26 01:02:56 +00006150PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006151PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006154 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006155 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006156 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006158 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159
Ezio Melottie7f90372012-10-05 03:33:31 +03006160 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006161 escape.
6162
Ezio Melottie7f90372012-10-05 03:33:31 +03006163 For UCS1 strings it's '\xxx', 4 bytes per source character.
6164 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6165 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006166 */
6167
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168 if (!PyUnicode_Check(unicode)) {
6169 PyErr_BadArgument();
6170 return NULL;
6171 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006172 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006173 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006174 }
Victor Stinner358af132015-10-12 22:36:57 +02006175
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006176 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 if (len == 0) {
6178 return PyBytes_FromStringAndSize(NULL, 0);
6179 }
6180
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006181 kind = PyUnicode_KIND(unicode);
6182 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006183 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6184 bytes, and 1 byte characters 4. */
6185 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006186 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006187 return PyErr_NoMemory();
6188 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006189 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006190 if (repr == NULL) {
6191 return NULL;
6192 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193
Victor Stinner62ec3312016-09-06 17:04:34 -07006194 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006195 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006196 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006197
Victor Stinner62ec3312016-09-06 17:04:34 -07006198 /* U+0000-U+00ff range */
6199 if (ch < 0x100) {
6200 if (ch >= ' ' && ch < 127) {
6201 if (ch != '\\') {
6202 /* Copy printable US ASCII as-is */
6203 *p++ = (char) ch;
6204 }
6205 /* Escape backslashes */
6206 else {
6207 *p++ = '\\';
6208 *p++ = '\\';
6209 }
6210 }
Victor Stinner358af132015-10-12 22:36:57 +02006211
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 /* Map special whitespace to '\t', \n', '\r' */
6213 else if (ch == '\t') {
6214 *p++ = '\\';
6215 *p++ = 't';
6216 }
6217 else if (ch == '\n') {
6218 *p++ = '\\';
6219 *p++ = 'n';
6220 }
6221 else if (ch == '\r') {
6222 *p++ = '\\';
6223 *p++ = 'r';
6224 }
6225
6226 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6227 else {
6228 *p++ = '\\';
6229 *p++ = 'x';
6230 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6231 *p++ = Py_hexdigits[ch & 0x000F];
6232 }
Tim Petersced69f82003-09-16 20:30:58 +00006233 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006234 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006235 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236 *p++ = '\\';
6237 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006238 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6239 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6240 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6241 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006242 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006243 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6244 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006245
Victor Stinner62ec3312016-09-06 17:04:34 -07006246 /* Make sure that the first two digits are zero */
6247 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006248 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 *p++ = 'U';
6250 *p++ = '0';
6251 *p++ = '0';
6252 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6253 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6254 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6255 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6256 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6257 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006259 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006260
Victor Stinner62ec3312016-09-06 17:04:34 -07006261 assert(p - PyBytes_AS_STRING(repr) > 0);
6262 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6263 return NULL;
6264 }
6265 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266}
6267
Alexander Belopolsky40018472011-02-26 01:02:56 +00006268PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006269PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6270 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006272 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006273 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006276 }
6277
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006278 result = PyUnicode_AsUnicodeEscapeString(tmp);
6279 Py_DECREF(tmp);
6280 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006281}
6282
6283/* --- Raw Unicode Escape Codec ------------------------------------------- */
6284
Alexander Belopolsky40018472011-02-26 01:02:56 +00006285PyObject *
6286PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006287 Py_ssize_t size,
6288 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006289{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006290 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006291 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006292 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006293 PyObject *errorHandler = NULL;
6294 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006295
Victor Stinner62ec3312016-09-06 17:04:34 -07006296 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006297 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006298 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006299
Guido van Rossumd57fd912000-03-10 22:53:23 +00006300 /* Escaped strings will always be longer than the resulting
6301 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006302 length after conversion to the true value. (But decoding error
6303 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006304 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006305 writer.min_length = size;
6306 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6307 goto onError;
6308 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006309
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310 end = s + size;
6311 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006312 unsigned char c = (unsigned char) *s++;
6313 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006314 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006315 Py_ssize_t startinpos;
6316 Py_ssize_t endinpos;
6317 const char *message;
6318
6319#define WRITE_CHAR(ch) \
6320 do { \
6321 if (ch <= writer.maxchar) { \
6322 assert(writer.pos < writer.size); \
6323 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6324 } \
6325 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6326 goto onError; \
6327 } \
6328 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006329
Benjamin Peterson29060642009-01-31 22:14:21 +00006330 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006331 if (c != '\\' || s >= end) {
6332 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006334 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006335
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 c = (unsigned char) *s++;
6337 if (c == 'u') {
6338 count = 4;
6339 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006341 else if (c == 'U') {
6342 count = 8;
6343 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006344 }
6345 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006346 assert(writer.pos < writer.size);
6347 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6348 WRITE_CHAR(c);
6349 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006350 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006351 startinpos = s - starts - 2;
6352
6353 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6354 for (ch = 0; count && s < end; ++s, --count) {
6355 c = (unsigned char)*s;
6356 ch <<= 4;
6357 if (c >= '0' && c <= '9') {
6358 ch += c - '0';
6359 }
6360 else if (c >= 'a' && c <= 'f') {
6361 ch += c - ('a' - 10);
6362 }
6363 else if (c >= 'A' && c <= 'F') {
6364 ch += c - ('A' - 10);
6365 }
6366 else {
6367 break;
6368 }
6369 }
6370 if (!count) {
6371 if (ch <= MAX_UNICODE) {
6372 WRITE_CHAR(ch);
6373 continue;
6374 }
6375 message = "\\Uxxxxxxxx out of range";
6376 }
6377
6378 endinpos = s-starts;
6379 writer.min_length = end - s + writer.pos;
6380 if (unicode_decode_call_errorhandler_writer(
6381 errors, &errorHandler,
6382 "rawunicodeescape", message,
6383 &starts, &end, &startinpos, &endinpos, &exc, &s,
6384 &writer)) {
6385 goto onError;
6386 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006387 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006388
6389#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006390 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391 Py_XDECREF(errorHandler);
6392 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006393 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006394
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006396 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397 Py_XDECREF(errorHandler);
6398 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006400
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401}
6402
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006403
Alexander Belopolsky40018472011-02-26 01:02:56 +00006404PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006405PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406{
Victor Stinner62ec3312016-09-06 17:04:34 -07006407 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006409 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006410 int kind;
6411 void *data;
6412 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006414 if (!PyUnicode_Check(unicode)) {
6415 PyErr_BadArgument();
6416 return NULL;
6417 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006418 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006419 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006420 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006421 kind = PyUnicode_KIND(unicode);
6422 data = PyUnicode_DATA(unicode);
6423 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006424 if (kind == PyUnicode_1BYTE_KIND) {
6425 return PyBytes_FromStringAndSize(data, len);
6426 }
Victor Stinner0e368262011-11-10 20:12:49 +01006427
Victor Stinner62ec3312016-09-06 17:04:34 -07006428 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6429 bytes, and 1 byte characters 4. */
6430 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006431
Victor Stinner62ec3312016-09-06 17:04:34 -07006432 if (len > PY_SSIZE_T_MAX / expandsize) {
6433 return PyErr_NoMemory();
6434 }
6435 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6436 if (repr == NULL) {
6437 return NULL;
6438 }
6439 if (len == 0) {
6440 return repr;
6441 }
6442
6443 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006444 for (pos = 0; pos < len; pos++) {
6445 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006446
Victor Stinner62ec3312016-09-06 17:04:34 -07006447 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6448 if (ch < 0x100) {
6449 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006450 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006451 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006452 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006453 *p++ = '\\';
6454 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006455 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6456 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6457 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6458 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006459 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006460 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6461 else {
6462 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6463 *p++ = '\\';
6464 *p++ = 'U';
6465 *p++ = '0';
6466 *p++ = '0';
6467 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6468 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6469 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6470 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6471 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6472 *p++ = Py_hexdigits[ch & 15];
6473 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006474 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006475
Victor Stinner62ec3312016-09-06 17:04:34 -07006476 assert(p > PyBytes_AS_STRING(repr));
6477 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6478 return NULL;
6479 }
6480 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006481}
6482
Alexander Belopolsky40018472011-02-26 01:02:56 +00006483PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006484PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6485 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006486{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006487 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006488 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006489 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006490 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006491 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6492 Py_DECREF(tmp);
6493 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494}
6495
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006496/* --- Unicode Internal Codec ------------------------------------------- */
6497
Alexander Belopolsky40018472011-02-26 01:02:56 +00006498PyObject *
6499_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006500 Py_ssize_t size,
6501 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006502{
6503 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006504 Py_ssize_t startinpos;
6505 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006506 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006507 const char *end;
6508 const char *reason;
6509 PyObject *errorHandler = NULL;
6510 PyObject *exc = NULL;
6511
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006512 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006513 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006514 1))
6515 return NULL;
6516
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006517 if (size < 0) {
6518 PyErr_BadInternalCall();
6519 return NULL;
6520 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006521 if (size == 0)
6522 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006523
Victor Stinner8f674cc2013-04-17 23:02:17 +02006524 _PyUnicodeWriter_Init(&writer);
6525 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6526 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006528 }
6529 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006530
Victor Stinner8f674cc2013-04-17 23:02:17 +02006531 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006532 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006533 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006534 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006535 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006536 endinpos = end-starts;
6537 reason = "truncated input";
6538 goto error;
6539 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006540 /* We copy the raw representation one byte at a time because the
6541 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006542 ((char *) &uch)[0] = s[0];
6543 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006544#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006545 ((char *) &uch)[2] = s[2];
6546 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006547#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006548 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006549#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006550 /* We have to sanity check the raw data, otherwise doom looms for
6551 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006552 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006553 endinpos = s - starts + Py_UNICODE_SIZE;
6554 reason = "illegal code point (> 0x10FFFF)";
6555 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006556 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006557#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006558 s += Py_UNICODE_SIZE;
6559#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006560 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006561 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006562 Py_UNICODE uch2;
6563 ((char *) &uch2)[0] = s[0];
6564 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006565 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006566 {
Victor Stinner551ac952011-11-29 22:58:13 +01006567 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006568 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006569 }
6570 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006571#endif
6572
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006573 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006574 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006575 continue;
6576
6577 error:
6578 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006579 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006580 errors, &errorHandler,
6581 "unicode_internal", reason,
6582 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006583 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006584 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006585 }
6586
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006587 Py_XDECREF(errorHandler);
6588 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006589 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006590
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006592 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006593 Py_XDECREF(errorHandler);
6594 Py_XDECREF(exc);
6595 return NULL;
6596}
6597
Guido van Rossumd57fd912000-03-10 22:53:23 +00006598/* --- Latin-1 Codec ------------------------------------------------------ */
6599
Alexander Belopolsky40018472011-02-26 01:02:56 +00006600PyObject *
6601PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006602 Py_ssize_t size,
6603 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006605 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006606 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006607}
6608
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006610static void
6611make_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{
6617 if (*exceptionObject == NULL) {
6618 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006619 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006620 encoding, unicode, startpos, endpos, reason);
6621 }
6622 else {
6623 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6624 goto onError;
6625 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6626 goto onError;
6627 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6628 goto onError;
6629 return;
6630 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006631 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006632 }
6633}
6634
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006636static void
6637raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006638 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006639 PyObject *unicode,
6640 Py_ssize_t startpos, Py_ssize_t endpos,
6641 const char *reason)
6642{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006643 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006644 encoding, unicode, startpos, endpos, reason);
6645 if (*exceptionObject != NULL)
6646 PyCodec_StrictErrors(*exceptionObject);
6647}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648
6649/* error handling callback helper:
6650 build arguments, call the callback and check the arguments,
6651 put the result into newpos and return the replacement string, which
6652 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006653static PyObject *
6654unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006655 PyObject **errorHandler,
6656 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006658 Py_ssize_t startpos, Py_ssize_t endpos,
6659 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006661 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 PyObject *restuple;
6664 PyObject *resunicode;
6665
6666 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006669 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670 }
6671
Benjamin Petersonbac79492012-01-14 13:34:47 -05006672 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673 return NULL;
6674 len = PyUnicode_GET_LENGTH(unicode);
6675
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006676 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006678 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006679 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006681 restuple = PyObject_CallFunctionObjArgs(
6682 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006683 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006685 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006686 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006687 Py_DECREF(restuple);
6688 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006689 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006690 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006691 &resunicode, newpos)) {
6692 Py_DECREF(restuple);
6693 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006694 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006695 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6696 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6697 Py_DECREF(restuple);
6698 return NULL;
6699 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006701 *newpos = len + *newpos;
6702 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006703 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 Py_DECREF(restuple);
6705 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006706 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 Py_INCREF(resunicode);
6708 Py_DECREF(restuple);
6709 return resunicode;
6710}
6711
Alexander Belopolsky40018472011-02-26 01:02:56 +00006712static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006713unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006714 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006715 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006717 /* input state */
6718 Py_ssize_t pos=0, size;
6719 int kind;
6720 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 /* pointer into the output */
6722 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006723 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6724 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006725 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006726 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006727 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006728 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006729 /* output object */
6730 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006731
Benjamin Petersonbac79492012-01-14 13:34:47 -05006732 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006733 return NULL;
6734 size = PyUnicode_GET_LENGTH(unicode);
6735 kind = PyUnicode_KIND(unicode);
6736 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006737 /* allocate enough for a simple encoding without
6738 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006739 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006740 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006741
6742 _PyBytesWriter_Init(&writer);
6743 str = _PyBytesWriter_Alloc(&writer, size);
6744 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006745 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006748 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006749
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006751 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006753 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006754 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006755 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006756 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006757 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006759 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006760 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006761 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006762
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006763 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006765
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006766 /* Only overallocate the buffer if it's not the last write */
6767 writer.overallocate = (collend < size);
6768
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006770 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006771 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006772
6773 switch (error_handler) {
6774 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006775 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006777
6778 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006779 memset(str, '?', collend - collstart);
6780 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006781 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006782 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006783 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006784 break;
Victor Stinner50149202015-09-22 00:26:54 +02006785
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006786 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006787 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006788 writer.min_size -= (collend - collstart);
6789 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006790 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006791 if (str == NULL)
6792 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006793 pos = collend;
6794 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006795
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006796 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006797 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006798 writer.min_size -= (collend - collstart);
6799 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006800 unicode, collstart, collend);
6801 if (str == NULL)
6802 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006803 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 break;
Victor Stinner50149202015-09-22 00:26:54 +02006805
Victor Stinnerc3713e92015-09-29 12:32:13 +02006806 case _Py_ERROR_SURROGATEESCAPE:
6807 for (i = collstart; i < collend; ++i) {
6808 ch = PyUnicode_READ(kind, data, i);
6809 if (ch < 0xdc80 || 0xdcff < ch) {
6810 /* Not a UTF-8b surrogate */
6811 break;
6812 }
6813 *str++ = (char)(ch - 0xdc00);
6814 ++pos;
6815 }
6816 if (i >= collend)
6817 break;
6818 collstart = pos;
6819 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006820 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006821
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006823 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6824 encoding, reason, unicode, &exc,
6825 collstart, collend, &newpos);
6826 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006827 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006828
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006829 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006830 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006831
Victor Stinner6bd525b2015-10-09 13:10:05 +02006832 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006833 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006834 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006835 PyBytes_AS_STRING(rep),
6836 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006837 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006838 else {
6839 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006840
Victor Stinner6bd525b2015-10-09 13:10:05 +02006841 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006843
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006844 if (limit == 256 ?
6845 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6846 !PyUnicode_IS_ASCII(rep))
6847 {
6848 /* Not all characters are smaller than limit */
6849 raise_encode_exception(&exc, encoding, unicode,
6850 collstart, collend, reason);
6851 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006852 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006853 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6854 str = _PyBytesWriter_WriteBytes(&writer, str,
6855 PyUnicode_DATA(rep),
6856 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03006858 if (str == NULL)
6859 goto onError;
6860
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006861 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006862 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006863 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006864
6865 /* If overallocation was disabled, ensure that it was the last
6866 write. Otherwise, we missed an optimization */
6867 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006868 }
6869 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006870
Victor Stinner50149202015-09-22 00:26:54 +02006871 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006872 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006873 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006874
6875 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006876 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006877 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006878 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006879 Py_XDECREF(exc);
6880 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006881}
6882
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006883/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006884PyObject *
6885PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006886 Py_ssize_t size,
6887 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006888{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006889 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006890 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006891 if (unicode == NULL)
6892 return NULL;
6893 result = unicode_encode_ucs1(unicode, errors, 256);
6894 Py_DECREF(unicode);
6895 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896}
6897
Alexander Belopolsky40018472011-02-26 01:02:56 +00006898PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006899_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006900{
6901 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006902 PyErr_BadArgument();
6903 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006904 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006905 if (PyUnicode_READY(unicode) == -1)
6906 return NULL;
6907 /* Fast path: if it is a one-byte string, construct
6908 bytes object directly. */
6909 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6910 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6911 PyUnicode_GET_LENGTH(unicode));
6912 /* Non-Latin-1 characters present. Defer to above function to
6913 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006914 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006915}
6916
6917PyObject*
6918PyUnicode_AsLatin1String(PyObject *unicode)
6919{
6920 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006921}
6922
6923/* --- 7-bit ASCII Codec -------------------------------------------------- */
6924
Alexander Belopolsky40018472011-02-26 01:02:56 +00006925PyObject *
6926PyUnicode_DecodeASCII(const char *s,
6927 Py_ssize_t size,
6928 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006930 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006931 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006932 int kind;
6933 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006934 Py_ssize_t startinpos;
6935 Py_ssize_t endinpos;
6936 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006937 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006938 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006939 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006940 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006941
Guido van Rossumd57fd912000-03-10 22:53:23 +00006942 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006943 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006944
Guido van Rossumd57fd912000-03-10 22:53:23 +00006945 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006946 if (size == 1 && (unsigned char)s[0] < 128)
6947 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006948
Victor Stinner8f674cc2013-04-17 23:02:17 +02006949 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006950 writer.min_length = size;
6951 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006952 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006953
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006954 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006955 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006956 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006957 writer.pos = outpos;
6958 if (writer.pos == size)
6959 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006960
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006961 s += writer.pos;
6962 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006963 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006964 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006966 PyUnicode_WRITE(kind, data, writer.pos, c);
6967 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006968 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006969 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006970 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006971
6972 /* byte outsize range 0x00..0x7f: call the error handler */
6973
6974 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006975 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006976
6977 switch (error_handler)
6978 {
6979 case _Py_ERROR_REPLACE:
6980 case _Py_ERROR_SURROGATEESCAPE:
6981 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006982 but we may switch to UCS2 at the first write */
6983 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6984 goto onError;
6985 kind = writer.kind;
6986 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006987
6988 if (error_handler == _Py_ERROR_REPLACE)
6989 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6990 else
6991 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6992 writer.pos++;
6993 ++s;
6994 break;
6995
6996 case _Py_ERROR_IGNORE:
6997 ++s;
6998 break;
6999
7000 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007001 startinpos = s-starts;
7002 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007003 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007004 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007005 "ascii", "ordinal not in range(128)",
7006 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007007 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007008 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007009 kind = writer.kind;
7010 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007011 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007012 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007013 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007014 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007015 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007016
Benjamin Peterson29060642009-01-31 22:14:21 +00007017 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007018 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007019 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007020 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007021 return NULL;
7022}
7023
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007024/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007025PyObject *
7026PyUnicode_EncodeASCII(const Py_UNICODE *p,
7027 Py_ssize_t size,
7028 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007029{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007030 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007031 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007032 if (unicode == NULL)
7033 return NULL;
7034 result = unicode_encode_ucs1(unicode, errors, 128);
7035 Py_DECREF(unicode);
7036 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007037}
7038
Alexander Belopolsky40018472011-02-26 01:02:56 +00007039PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007040_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007041{
7042 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007043 PyErr_BadArgument();
7044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007046 if (PyUnicode_READY(unicode) == -1)
7047 return NULL;
7048 /* Fast path: if it is an ASCII-only string, construct bytes object
7049 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007050 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007051 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7052 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007053 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007054}
7055
7056PyObject *
7057PyUnicode_AsASCIIString(PyObject *unicode)
7058{
7059 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007060}
7061
Steve Dowercc16be82016-09-08 10:35:16 -07007062#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007063
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007064/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007065
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007066#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007067#define NEED_RETRY
7068#endif
7069
Victor Stinner3a50e702011-10-18 21:21:00 +02007070#ifndef WC_ERR_INVALID_CHARS
7071# define WC_ERR_INVALID_CHARS 0x0080
7072#endif
7073
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007074static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007075code_page_name(UINT code_page, PyObject **obj)
7076{
7077 *obj = NULL;
7078 if (code_page == CP_ACP)
7079 return "mbcs";
7080 if (code_page == CP_UTF7)
7081 return "CP_UTF7";
7082 if (code_page == CP_UTF8)
7083 return "CP_UTF8";
7084
7085 *obj = PyBytes_FromFormat("cp%u", code_page);
7086 if (*obj == NULL)
7087 return NULL;
7088 return PyBytes_AS_STRING(*obj);
7089}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090
Victor Stinner3a50e702011-10-18 21:21:00 +02007091static DWORD
7092decode_code_page_flags(UINT code_page)
7093{
7094 if (code_page == CP_UTF7) {
7095 /* The CP_UTF7 decoder only supports flags=0 */
7096 return 0;
7097 }
7098 else
7099 return MB_ERR_INVALID_CHARS;
7100}
7101
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007103 * Decode a byte string from a Windows code page into unicode object in strict
7104 * mode.
7105 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007106 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7107 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007108 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007109static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007110decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007111 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 const char *in,
7113 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114{
Victor Stinner3a50e702011-10-18 21:21:00 +02007115 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007116 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007117 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118
7119 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007120 assert(insize > 0);
7121 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7122 if (outsize <= 0)
7123 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007124
7125 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007126 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007127 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007128 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007129 if (*v == NULL)
7130 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007131 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132 }
7133 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007134 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007136 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007137 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007139 }
7140
7141 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007142 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7143 if (outsize <= 0)
7144 goto error;
7145 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007146
Victor Stinner3a50e702011-10-18 21:21:00 +02007147error:
7148 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7149 return -2;
7150 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007151 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007152}
7153
Victor Stinner3a50e702011-10-18 21:21:00 +02007154/*
7155 * Decode a byte string from a code page into unicode object with an error
7156 * handler.
7157 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007158 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 * UnicodeDecodeError exception and returns -1 on error.
7160 */
7161static int
7162decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007163 PyObject **v,
7164 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007165 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007166{
7167 const char *startin = in;
7168 const char *endin = in + size;
7169 const DWORD flags = decode_code_page_flags(code_page);
7170 /* Ideally, we should get reason from FormatMessage. This is the Windows
7171 2000 English version of the message. */
7172 const char *reason = "No mapping for the Unicode character exists "
7173 "in the target code page.";
7174 /* each step cannot decode more than 1 character, but a character can be
7175 represented as a surrogate pair */
7176 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007177 int insize;
7178 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 PyObject *errorHandler = NULL;
7180 PyObject *exc = NULL;
7181 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007182 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 DWORD err;
7184 int ret = -1;
7185
7186 assert(size > 0);
7187
7188 encoding = code_page_name(code_page, &encoding_obj);
7189 if (encoding == NULL)
7190 return -1;
7191
Victor Stinner7d00cc12014-03-17 23:08:06 +01007192 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7194 UnicodeDecodeError. */
7195 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7196 if (exc != NULL) {
7197 PyCodec_StrictErrors(exc);
7198 Py_CLEAR(exc);
7199 }
7200 goto error;
7201 }
7202
7203 if (*v == NULL) {
7204 /* Create unicode object */
7205 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7206 PyErr_NoMemory();
7207 goto error;
7208 }
Victor Stinnerab595942011-12-17 04:59:06 +01007209 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007210 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007211 if (*v == NULL)
7212 goto error;
7213 startout = PyUnicode_AS_UNICODE(*v);
7214 }
7215 else {
7216 /* Extend unicode object */
7217 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7218 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7219 PyErr_NoMemory();
7220 goto error;
7221 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007222 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 goto error;
7224 startout = PyUnicode_AS_UNICODE(*v) + n;
7225 }
7226
7227 /* Decode the byte string character per character */
7228 out = startout;
7229 while (in < endin)
7230 {
7231 /* Decode a character */
7232 insize = 1;
7233 do
7234 {
7235 outsize = MultiByteToWideChar(code_page, flags,
7236 in, insize,
7237 buffer, Py_ARRAY_LENGTH(buffer));
7238 if (outsize > 0)
7239 break;
7240 err = GetLastError();
7241 if (err != ERROR_NO_UNICODE_TRANSLATION
7242 && err != ERROR_INSUFFICIENT_BUFFER)
7243 {
7244 PyErr_SetFromWindowsErr(0);
7245 goto error;
7246 }
7247 insize++;
7248 }
7249 /* 4=maximum length of a UTF-8 sequence */
7250 while (insize <= 4 && (in + insize) <= endin);
7251
7252 if (outsize <= 0) {
7253 Py_ssize_t startinpos, endinpos, outpos;
7254
Victor Stinner7d00cc12014-03-17 23:08:06 +01007255 /* last character in partial decode? */
7256 if (in + insize >= endin && !final)
7257 break;
7258
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 startinpos = in - startin;
7260 endinpos = startinpos + 1;
7261 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007262 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 errors, &errorHandler,
7264 encoding, reason,
7265 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007266 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 {
7268 goto error;
7269 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007270 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 }
7272 else {
7273 in += insize;
7274 memcpy(out, buffer, outsize * sizeof(wchar_t));
7275 out += outsize;
7276 }
7277 }
7278
7279 /* write a NUL character at the end */
7280 *out = 0;
7281
7282 /* Extend unicode object */
7283 outsize = out - startout;
7284 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007285 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007287 /* (in - startin) <= size and size is an int */
7288 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007289
7290error:
7291 Py_XDECREF(encoding_obj);
7292 Py_XDECREF(errorHandler);
7293 Py_XDECREF(exc);
7294 return ret;
7295}
7296
Victor Stinner3a50e702011-10-18 21:21:00 +02007297static PyObject *
7298decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007299 const char *s, Py_ssize_t size,
7300 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007301{
Victor Stinner76a31a62011-11-04 00:05:13 +01007302 PyObject *v = NULL;
7303 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007304
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 if (code_page < 0) {
7306 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7307 return NULL;
7308 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007309 if (size < 0) {
7310 PyErr_BadInternalCall();
7311 return NULL;
7312 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007313
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007314 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007315 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316
Victor Stinner76a31a62011-11-04 00:05:13 +01007317 do
7318 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007319#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007320 if (size > INT_MAX) {
7321 chunk_size = INT_MAX;
7322 final = 0;
7323 done = 0;
7324 }
7325 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007326#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007327 {
7328 chunk_size = (int)size;
7329 final = (consumed == NULL);
7330 done = 1;
7331 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007332
Victor Stinner76a31a62011-11-04 00:05:13 +01007333 if (chunk_size == 0 && done) {
7334 if (v != NULL)
7335 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007336 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007337 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007338
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 converted = decode_code_page_strict(code_page, &v,
7340 s, chunk_size);
7341 if (converted == -2)
7342 converted = decode_code_page_errors(code_page, &v,
7343 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007344 errors, final);
7345 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007346
7347 if (converted < 0) {
7348 Py_XDECREF(v);
7349 return NULL;
7350 }
7351
7352 if (consumed)
7353 *consumed += converted;
7354
7355 s += converted;
7356 size -= converted;
7357 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007358
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007359 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007360}
7361
Alexander Belopolsky40018472011-02-26 01:02:56 +00007362PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007363PyUnicode_DecodeCodePageStateful(int code_page,
7364 const char *s,
7365 Py_ssize_t size,
7366 const char *errors,
7367 Py_ssize_t *consumed)
7368{
7369 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7370}
7371
7372PyObject *
7373PyUnicode_DecodeMBCSStateful(const char *s,
7374 Py_ssize_t size,
7375 const char *errors,
7376 Py_ssize_t *consumed)
7377{
7378 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7379}
7380
7381PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007382PyUnicode_DecodeMBCS(const char *s,
7383 Py_ssize_t size,
7384 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007385{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7387}
7388
Victor Stinner3a50e702011-10-18 21:21:00 +02007389static DWORD
7390encode_code_page_flags(UINT code_page, const char *errors)
7391{
7392 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007393 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 }
7395 else if (code_page == CP_UTF7) {
7396 /* CP_UTF7 only supports flags=0 */
7397 return 0;
7398 }
7399 else {
7400 if (errors != NULL && strcmp(errors, "replace") == 0)
7401 return 0;
7402 else
7403 return WC_NO_BEST_FIT_CHARS;
7404 }
7405}
7406
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007407/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 * Encode a Unicode string to a Windows code page into a byte string in strict
7409 * mode.
7410 *
7411 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007412 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007413 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007414static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007415encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007416 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007418{
Victor Stinner554f3f02010-06-16 23:33:54 +00007419 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 BOOL *pusedDefaultChar = &usedDefaultChar;
7421 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007422 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007423 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007424 const DWORD flags = encode_code_page_flags(code_page, NULL);
7425 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007426 /* Create a substring so that we can get the UTF-16 representation
7427 of just the slice under consideration. */
7428 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007429
Martin v. Löwis3d325192011-11-04 18:23:06 +01007430 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007431
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007433 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007435 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007436
Victor Stinner2fc507f2011-11-04 20:06:39 +01007437 substring = PyUnicode_Substring(unicode, offset, offset+len);
7438 if (substring == NULL)
7439 return -1;
7440 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7441 if (p == NULL) {
7442 Py_DECREF(substring);
7443 return -1;
7444 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007445 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007446
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007447 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007449 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 NULL, 0,
7451 NULL, pusedDefaultChar);
7452 if (outsize <= 0)
7453 goto error;
7454 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 if (pusedDefaultChar && *pusedDefaultChar) {
7456 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007459
Victor Stinner3a50e702011-10-18 21:21:00 +02007460 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007461 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 if (*outbytes == NULL) {
7464 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007465 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007466 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007468 }
7469 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007470 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 const Py_ssize_t n = PyBytes_Size(*outbytes);
7472 if (outsize > PY_SSIZE_T_MAX - n) {
7473 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007475 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007476 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007477 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7478 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007480 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007482 }
7483
7484 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007486 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 out, outsize,
7488 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007489 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 if (outsize <= 0)
7491 goto error;
7492 if (pusedDefaultChar && *pusedDefaultChar)
7493 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007494 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007495
Victor Stinner3a50e702011-10-18 21:21:00 +02007496error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007497 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7499 return -2;
7500 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007501 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007502}
7503
Victor Stinner3a50e702011-10-18 21:21:00 +02007504/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007505 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007506 * error handler.
7507 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007508 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 * -1 on other error.
7510 */
7511static int
7512encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007513 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007514 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007515{
Victor Stinner3a50e702011-10-18 21:21:00 +02007516 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007517 Py_ssize_t pos = unicode_offset;
7518 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007519 /* Ideally, we should get reason from FormatMessage. This is the Windows
7520 2000 English version of the message. */
7521 const char *reason = "invalid character";
7522 /* 4=maximum length of a UTF-8 sequence */
7523 char buffer[4];
7524 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7525 Py_ssize_t outsize;
7526 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 PyObject *errorHandler = NULL;
7528 PyObject *exc = NULL;
7529 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007530 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 PyObject *rep;
7533 int ret = -1;
7534
7535 assert(insize > 0);
7536
7537 encoding = code_page_name(code_page, &encoding_obj);
7538 if (encoding == NULL)
7539 return -1;
7540
7541 if (errors == NULL || strcmp(errors, "strict") == 0) {
7542 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7543 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007544 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007545 if (exc != NULL) {
7546 PyCodec_StrictErrors(exc);
7547 Py_DECREF(exc);
7548 }
7549 Py_XDECREF(encoding_obj);
7550 return -1;
7551 }
7552
7553 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7554 pusedDefaultChar = &usedDefaultChar;
7555 else
7556 pusedDefaultChar = NULL;
7557
7558 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7559 PyErr_NoMemory();
7560 goto error;
7561 }
7562 outsize = insize * Py_ARRAY_LENGTH(buffer);
7563
7564 if (*outbytes == NULL) {
7565 /* Create string object */
7566 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7567 if (*outbytes == NULL)
7568 goto error;
7569 out = PyBytes_AS_STRING(*outbytes);
7570 }
7571 else {
7572 /* Extend string object */
7573 Py_ssize_t n = PyBytes_Size(*outbytes);
7574 if (n > PY_SSIZE_T_MAX - outsize) {
7575 PyErr_NoMemory();
7576 goto error;
7577 }
7578 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7579 goto error;
7580 out = PyBytes_AS_STRING(*outbytes) + n;
7581 }
7582
7583 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007584 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007585 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007586 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7587 wchar_t chars[2];
7588 int charsize;
7589 if (ch < 0x10000) {
7590 chars[0] = (wchar_t)ch;
7591 charsize = 1;
7592 }
7593 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007594 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7595 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007596 charsize = 2;
7597 }
7598
Victor Stinner3a50e702011-10-18 21:21:00 +02007599 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007600 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007601 buffer, Py_ARRAY_LENGTH(buffer),
7602 NULL, pusedDefaultChar);
7603 if (outsize > 0) {
7604 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7605 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007606 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007607 memcpy(out, buffer, outsize);
7608 out += outsize;
7609 continue;
7610 }
7611 }
7612 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7613 PyErr_SetFromWindowsErr(0);
7614 goto error;
7615 }
7616
Victor Stinner3a50e702011-10-18 21:21:00 +02007617 rep = unicode_encode_call_errorhandler(
7618 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007619 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007620 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007621 if (rep == NULL)
7622 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007623 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007624
7625 if (PyBytes_Check(rep)) {
7626 outsize = PyBytes_GET_SIZE(rep);
7627 if (outsize != 1) {
7628 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7629 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7630 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7631 Py_DECREF(rep);
7632 goto error;
7633 }
7634 out = PyBytes_AS_STRING(*outbytes) + offset;
7635 }
7636 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7637 out += outsize;
7638 }
7639 else {
7640 Py_ssize_t i;
7641 enum PyUnicode_Kind kind;
7642 void *data;
7643
Benjamin Petersonbac79492012-01-14 13:34:47 -05007644 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007645 Py_DECREF(rep);
7646 goto error;
7647 }
7648
7649 outsize = PyUnicode_GET_LENGTH(rep);
7650 if (outsize != 1) {
7651 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7652 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7653 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7654 Py_DECREF(rep);
7655 goto error;
7656 }
7657 out = PyBytes_AS_STRING(*outbytes) + offset;
7658 }
7659 kind = PyUnicode_KIND(rep);
7660 data = PyUnicode_DATA(rep);
7661 for (i=0; i < outsize; i++) {
7662 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7663 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007664 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007665 encoding, unicode,
7666 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007667 "unable to encode error handler result to ASCII");
7668 Py_DECREF(rep);
7669 goto error;
7670 }
7671 *out = (unsigned char)ch;
7672 out++;
7673 }
7674 }
7675 Py_DECREF(rep);
7676 }
7677 /* write a NUL byte */
7678 *out = 0;
7679 outsize = out - PyBytes_AS_STRING(*outbytes);
7680 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7681 if (_PyBytes_Resize(outbytes, outsize) < 0)
7682 goto error;
7683 ret = 0;
7684
7685error:
7686 Py_XDECREF(encoding_obj);
7687 Py_XDECREF(errorHandler);
7688 Py_XDECREF(exc);
7689 return ret;
7690}
7691
Victor Stinner3a50e702011-10-18 21:21:00 +02007692static PyObject *
7693encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007694 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007695 const char *errors)
7696{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007697 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007698 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007699 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007700 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007701
Victor Stinner29dacf22015-01-26 16:41:32 +01007702 if (!PyUnicode_Check(unicode)) {
7703 PyErr_BadArgument();
7704 return NULL;
7705 }
7706
Benjamin Petersonbac79492012-01-14 13:34:47 -05007707 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007708 return NULL;
7709 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007710
Victor Stinner3a50e702011-10-18 21:21:00 +02007711 if (code_page < 0) {
7712 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7713 return NULL;
7714 }
7715
Martin v. Löwis3d325192011-11-04 18:23:06 +01007716 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007717 return PyBytes_FromStringAndSize(NULL, 0);
7718
Victor Stinner7581cef2011-11-03 22:32:33 +01007719 offset = 0;
7720 do
7721 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007722#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007723 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007724 chunks. */
7725 if (len > INT_MAX/2) {
7726 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007727 done = 0;
7728 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007729 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007730#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007731 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007732 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007733 done = 1;
7734 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007735
Victor Stinner76a31a62011-11-04 00:05:13 +01007736 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007737 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007738 errors);
7739 if (ret == -2)
7740 ret = encode_code_page_errors(code_page, &outbytes,
7741 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007742 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007743 if (ret < 0) {
7744 Py_XDECREF(outbytes);
7745 return NULL;
7746 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007747
Victor Stinner7581cef2011-11-03 22:32:33 +01007748 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007749 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007750 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007751
Victor Stinner3a50e702011-10-18 21:21:00 +02007752 return outbytes;
7753}
7754
7755PyObject *
7756PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7757 Py_ssize_t size,
7758 const char *errors)
7759{
Victor Stinner7581cef2011-11-03 22:32:33 +01007760 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007761 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007762 if (unicode == NULL)
7763 return NULL;
7764 res = encode_code_page(CP_ACP, unicode, errors);
7765 Py_DECREF(unicode);
7766 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007767}
7768
7769PyObject *
7770PyUnicode_EncodeCodePage(int code_page,
7771 PyObject *unicode,
7772 const char *errors)
7773{
Victor Stinner7581cef2011-11-03 22:32:33 +01007774 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007775}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007776
Alexander Belopolsky40018472011-02-26 01:02:56 +00007777PyObject *
7778PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007779{
Victor Stinner7581cef2011-11-03 22:32:33 +01007780 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007781}
7782
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007783#undef NEED_RETRY
7784
Steve Dowercc16be82016-09-08 10:35:16 -07007785#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007786
Guido van Rossumd57fd912000-03-10 22:53:23 +00007787/* --- Character Mapping Codec -------------------------------------------- */
7788
Victor Stinnerfb161b12013-04-18 01:44:27 +02007789static int
7790charmap_decode_string(const char *s,
7791 Py_ssize_t size,
7792 PyObject *mapping,
7793 const char *errors,
7794 _PyUnicodeWriter *writer)
7795{
7796 const char *starts = s;
7797 const char *e;
7798 Py_ssize_t startinpos, endinpos;
7799 PyObject *errorHandler = NULL, *exc = NULL;
7800 Py_ssize_t maplen;
7801 enum PyUnicode_Kind mapkind;
7802 void *mapdata;
7803 Py_UCS4 x;
7804 unsigned char ch;
7805
7806 if (PyUnicode_READY(mapping) == -1)
7807 return -1;
7808
7809 maplen = PyUnicode_GET_LENGTH(mapping);
7810 mapdata = PyUnicode_DATA(mapping);
7811 mapkind = PyUnicode_KIND(mapping);
7812
7813 e = s + size;
7814
7815 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7816 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7817 * is disabled in encoding aliases, latin1 is preferred because
7818 * its implementation is faster. */
7819 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7820 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7821 Py_UCS4 maxchar = writer->maxchar;
7822
7823 assert (writer->kind == PyUnicode_1BYTE_KIND);
7824 while (s < e) {
7825 ch = *s;
7826 x = mapdata_ucs1[ch];
7827 if (x > maxchar) {
7828 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7829 goto onError;
7830 maxchar = writer->maxchar;
7831 outdata = (Py_UCS1 *)writer->data;
7832 }
7833 outdata[writer->pos] = x;
7834 writer->pos++;
7835 ++s;
7836 }
7837 return 0;
7838 }
7839
7840 while (s < e) {
7841 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7842 enum PyUnicode_Kind outkind = writer->kind;
7843 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7844 if (outkind == PyUnicode_1BYTE_KIND) {
7845 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7846 Py_UCS4 maxchar = writer->maxchar;
7847 while (s < e) {
7848 ch = *s;
7849 x = mapdata_ucs2[ch];
7850 if (x > maxchar)
7851 goto Error;
7852 outdata[writer->pos] = x;
7853 writer->pos++;
7854 ++s;
7855 }
7856 break;
7857 }
7858 else if (outkind == PyUnicode_2BYTE_KIND) {
7859 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7860 while (s < e) {
7861 ch = *s;
7862 x = mapdata_ucs2[ch];
7863 if (x == 0xFFFE)
7864 goto Error;
7865 outdata[writer->pos] = x;
7866 writer->pos++;
7867 ++s;
7868 }
7869 break;
7870 }
7871 }
7872 ch = *s;
7873
7874 if (ch < maplen)
7875 x = PyUnicode_READ(mapkind, mapdata, ch);
7876 else
7877 x = 0xfffe; /* invalid value */
7878Error:
7879 if (x == 0xfffe)
7880 {
7881 /* undefined mapping */
7882 startinpos = s-starts;
7883 endinpos = startinpos+1;
7884 if (unicode_decode_call_errorhandler_writer(
7885 errors, &errorHandler,
7886 "charmap", "character maps to <undefined>",
7887 &starts, &e, &startinpos, &endinpos, &exc, &s,
7888 writer)) {
7889 goto onError;
7890 }
7891 continue;
7892 }
7893
7894 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7895 goto onError;
7896 ++s;
7897 }
7898 Py_XDECREF(errorHandler);
7899 Py_XDECREF(exc);
7900 return 0;
7901
7902onError:
7903 Py_XDECREF(errorHandler);
7904 Py_XDECREF(exc);
7905 return -1;
7906}
7907
7908static int
7909charmap_decode_mapping(const char *s,
7910 Py_ssize_t size,
7911 PyObject *mapping,
7912 const char *errors,
7913 _PyUnicodeWriter *writer)
7914{
7915 const char *starts = s;
7916 const char *e;
7917 Py_ssize_t startinpos, endinpos;
7918 PyObject *errorHandler = NULL, *exc = NULL;
7919 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007920 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007921
7922 e = s + size;
7923
7924 while (s < e) {
7925 ch = *s;
7926
7927 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7928 key = PyLong_FromLong((long)ch);
7929 if (key == NULL)
7930 goto onError;
7931
7932 item = PyObject_GetItem(mapping, key);
7933 Py_DECREF(key);
7934 if (item == NULL) {
7935 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7936 /* No mapping found means: mapping is undefined. */
7937 PyErr_Clear();
7938 goto Undefined;
7939 } else
7940 goto onError;
7941 }
7942
7943 /* Apply mapping */
7944 if (item == Py_None)
7945 goto Undefined;
7946 if (PyLong_Check(item)) {
7947 long value = PyLong_AS_LONG(item);
7948 if (value == 0xFFFE)
7949 goto Undefined;
7950 if (value < 0 || value > MAX_UNICODE) {
7951 PyErr_Format(PyExc_TypeError,
7952 "character mapping must be in range(0x%lx)",
7953 (unsigned long)MAX_UNICODE + 1);
7954 goto onError;
7955 }
7956
7957 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7958 goto onError;
7959 }
7960 else if (PyUnicode_Check(item)) {
7961 if (PyUnicode_READY(item) == -1)
7962 goto onError;
7963 if (PyUnicode_GET_LENGTH(item) == 1) {
7964 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7965 if (value == 0xFFFE)
7966 goto Undefined;
7967 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7968 goto onError;
7969 }
7970 else {
7971 writer->overallocate = 1;
7972 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7973 goto onError;
7974 }
7975 }
7976 else {
7977 /* wrong return value */
7978 PyErr_SetString(PyExc_TypeError,
7979 "character mapping must return integer, None or str");
7980 goto onError;
7981 }
7982 Py_CLEAR(item);
7983 ++s;
7984 continue;
7985
7986Undefined:
7987 /* undefined mapping */
7988 Py_CLEAR(item);
7989 startinpos = s-starts;
7990 endinpos = startinpos+1;
7991 if (unicode_decode_call_errorhandler_writer(
7992 errors, &errorHandler,
7993 "charmap", "character maps to <undefined>",
7994 &starts, &e, &startinpos, &endinpos, &exc, &s,
7995 writer)) {
7996 goto onError;
7997 }
7998 }
7999 Py_XDECREF(errorHandler);
8000 Py_XDECREF(exc);
8001 return 0;
8002
8003onError:
8004 Py_XDECREF(item);
8005 Py_XDECREF(errorHandler);
8006 Py_XDECREF(exc);
8007 return -1;
8008}
8009
Alexander Belopolsky40018472011-02-26 01:02:56 +00008010PyObject *
8011PyUnicode_DecodeCharmap(const char *s,
8012 Py_ssize_t size,
8013 PyObject *mapping,
8014 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008016 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008017
Guido van Rossumd57fd912000-03-10 22:53:23 +00008018 /* Default to Latin-1 */
8019 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008021
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008023 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008024 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008025 writer.min_length = size;
8026 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008027 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008028
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008029 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008030 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8031 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008032 }
8033 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008034 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8035 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008036 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008037 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008038
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008040 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008041 return NULL;
8042}
8043
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008044/* Charmap encoding: the lookup table */
8045
Alexander Belopolsky40018472011-02-26 01:02:56 +00008046struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 PyObject_HEAD
8048 unsigned char level1[32];
8049 int count2, count3;
8050 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008051};
8052
8053static PyObject*
8054encoding_map_size(PyObject *obj, PyObject* args)
8055{
8056 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008059}
8060
8061static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008062 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 PyDoc_STR("Return the size (in bytes) of this object") },
8064 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065};
8066
8067static void
8068encoding_map_dealloc(PyObject* o)
8069{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008070 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008071}
8072
8073static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008074 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 "EncodingMap", /*tp_name*/
8076 sizeof(struct encoding_map), /*tp_basicsize*/
8077 0, /*tp_itemsize*/
8078 /* methods */
8079 encoding_map_dealloc, /*tp_dealloc*/
8080 0, /*tp_print*/
8081 0, /*tp_getattr*/
8082 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008083 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 0, /*tp_repr*/
8085 0, /*tp_as_number*/
8086 0, /*tp_as_sequence*/
8087 0, /*tp_as_mapping*/
8088 0, /*tp_hash*/
8089 0, /*tp_call*/
8090 0, /*tp_str*/
8091 0, /*tp_getattro*/
8092 0, /*tp_setattro*/
8093 0, /*tp_as_buffer*/
8094 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8095 0, /*tp_doc*/
8096 0, /*tp_traverse*/
8097 0, /*tp_clear*/
8098 0, /*tp_richcompare*/
8099 0, /*tp_weaklistoffset*/
8100 0, /*tp_iter*/
8101 0, /*tp_iternext*/
8102 encoding_map_methods, /*tp_methods*/
8103 0, /*tp_members*/
8104 0, /*tp_getset*/
8105 0, /*tp_base*/
8106 0, /*tp_dict*/
8107 0, /*tp_descr_get*/
8108 0, /*tp_descr_set*/
8109 0, /*tp_dictoffset*/
8110 0, /*tp_init*/
8111 0, /*tp_alloc*/
8112 0, /*tp_new*/
8113 0, /*tp_free*/
8114 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008115};
8116
8117PyObject*
8118PyUnicode_BuildEncodingMap(PyObject* string)
8119{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008120 PyObject *result;
8121 struct encoding_map *mresult;
8122 int i;
8123 int need_dict = 0;
8124 unsigned char level1[32];
8125 unsigned char level2[512];
8126 unsigned char *mlevel1, *mlevel2, *mlevel3;
8127 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008128 int kind;
8129 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008130 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008131 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008133 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 PyErr_BadArgument();
8135 return NULL;
8136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008137 kind = PyUnicode_KIND(string);
8138 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008139 length = PyUnicode_GET_LENGTH(string);
8140 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141 memset(level1, 0xFF, sizeof level1);
8142 memset(level2, 0xFF, sizeof level2);
8143
8144 /* If there isn't a one-to-one mapping of NULL to \0,
8145 or if there are non-BMP characters, we need to use
8146 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008147 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008149 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008150 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008151 ch = PyUnicode_READ(kind, data, i);
8152 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153 need_dict = 1;
8154 break;
8155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008156 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 /* unmapped character */
8158 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008159 l1 = ch >> 11;
8160 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008161 if (level1[l1] == 0xFF)
8162 level1[l1] = count2++;
8163 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008164 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008165 }
8166
8167 if (count2 >= 0xFF || count3 >= 0xFF)
8168 need_dict = 1;
8169
8170 if (need_dict) {
8171 PyObject *result = PyDict_New();
8172 PyObject *key, *value;
8173 if (!result)
8174 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008175 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008176 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008177 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008178 if (!key || !value)
8179 goto failed1;
8180 if (PyDict_SetItem(result, key, value) == -1)
8181 goto failed1;
8182 Py_DECREF(key);
8183 Py_DECREF(value);
8184 }
8185 return result;
8186 failed1:
8187 Py_XDECREF(key);
8188 Py_XDECREF(value);
8189 Py_DECREF(result);
8190 return NULL;
8191 }
8192
8193 /* Create a three-level trie */
8194 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8195 16*count2 + 128*count3 - 1);
8196 if (!result)
8197 return PyErr_NoMemory();
8198 PyObject_Init(result, &EncodingMapType);
8199 mresult = (struct encoding_map*)result;
8200 mresult->count2 = count2;
8201 mresult->count3 = count3;
8202 mlevel1 = mresult->level1;
8203 mlevel2 = mresult->level23;
8204 mlevel3 = mresult->level23 + 16*count2;
8205 memcpy(mlevel1, level1, 32);
8206 memset(mlevel2, 0xFF, 16*count2);
8207 memset(mlevel3, 0, 128*count3);
8208 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008209 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008210 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008211 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8212 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213 /* unmapped character */
8214 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008215 o1 = ch>>11;
8216 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008217 i2 = 16*mlevel1[o1] + o2;
8218 if (mlevel2[i2] == 0xFF)
8219 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008220 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008221 i3 = 128*mlevel2[i2] + o3;
8222 mlevel3[i3] = i;
8223 }
8224 return result;
8225}
8226
8227static int
Victor Stinner22168992011-11-20 17:09:18 +01008228encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008229{
8230 struct encoding_map *map = (struct encoding_map*)mapping;
8231 int l1 = c>>11;
8232 int l2 = (c>>7) & 0xF;
8233 int l3 = c & 0x7F;
8234 int i;
8235
Victor Stinner22168992011-11-20 17:09:18 +01008236 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008238 if (c == 0)
8239 return 0;
8240 /* level 1*/
8241 i = map->level1[l1];
8242 if (i == 0xFF) {
8243 return -1;
8244 }
8245 /* level 2*/
8246 i = map->level23[16*i+l2];
8247 if (i == 0xFF) {
8248 return -1;
8249 }
8250 /* level 3 */
8251 i = map->level23[16*map->count2 + 128*i + l3];
8252 if (i == 0) {
8253 return -1;
8254 }
8255 return i;
8256}
8257
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008258/* Lookup the character ch in the mapping. If the character
8259 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008260 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008261static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008262charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263{
Christian Heimes217cfd12007-12-02 14:31:20 +00008264 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 PyObject *x;
8266
8267 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008269 x = PyObject_GetItem(mapping, w);
8270 Py_DECREF(w);
8271 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8273 /* No mapping found means: mapping is undefined. */
8274 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008275 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 } else
8277 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008279 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008281 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 long value = PyLong_AS_LONG(x);
8283 if (value < 0 || value > 255) {
8284 PyErr_SetString(PyExc_TypeError,
8285 "character mapping must be in range(256)");
8286 Py_DECREF(x);
8287 return NULL;
8288 }
8289 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008291 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008293 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 /* wrong return value */
8295 PyErr_Format(PyExc_TypeError,
8296 "character mapping must return integer, bytes or None, not %.400s",
8297 x->ob_type->tp_name);
8298 Py_DECREF(x);
8299 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300 }
8301}
8302
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008303static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008304charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008306 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8307 /* exponentially overallocate to minimize reallocations */
8308 if (requiredsize < 2*outsize)
8309 requiredsize = 2*outsize;
8310 if (_PyBytes_Resize(outobj, requiredsize))
8311 return -1;
8312 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008313}
8314
Benjamin Peterson14339b62009-01-31 16:36:08 +00008315typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008317} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008318/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008319 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320 space is available. Return a new reference to the object that
8321 was put in the output buffer, or Py_None, if the mapping was undefined
8322 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008323 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008324static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008325charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008326 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008328 PyObject *rep;
8329 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008330 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331
Christian Heimes90aa7642007-12-19 02:45:37 +00008332 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008333 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008335 if (res == -1)
8336 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 if (outsize<requiredsize)
8338 if (charmapencode_resize(outobj, outpos, requiredsize))
8339 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008340 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 outstart[(*outpos)++] = (char)res;
8342 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008343 }
8344
8345 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008348 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 Py_DECREF(rep);
8350 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008351 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 if (PyLong_Check(rep)) {
8353 Py_ssize_t requiredsize = *outpos+1;
8354 if (outsize<requiredsize)
8355 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8356 Py_DECREF(rep);
8357 return enc_EXCEPTION;
8358 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008359 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008361 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 else {
8363 const char *repchars = PyBytes_AS_STRING(rep);
8364 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8365 Py_ssize_t requiredsize = *outpos+repsize;
8366 if (outsize<requiredsize)
8367 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8368 Py_DECREF(rep);
8369 return enc_EXCEPTION;
8370 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008371 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 memcpy(outstart + *outpos, repchars, repsize);
8373 *outpos += repsize;
8374 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008376 Py_DECREF(rep);
8377 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378}
8379
8380/* handle an error in PyUnicode_EncodeCharmap
8381 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008382static int
8383charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008384 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008386 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008387 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388{
8389 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008390 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008391 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008392 enum PyUnicode_Kind kind;
8393 void *data;
8394 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008395 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008396 Py_ssize_t collstartpos = *inpos;
8397 Py_ssize_t collendpos = *inpos+1;
8398 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008399 const char *encoding = "charmap";
8400 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008401 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008402 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008403 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404
Benjamin Petersonbac79492012-01-14 13:34:47 -05008405 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008406 return -1;
8407 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 /* find all unencodable characters */
8409 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008410 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008411 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008412 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008413 val = encoding_map_lookup(ch, mapping);
8414 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 break;
8416 ++collendpos;
8417 continue;
8418 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008419
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008420 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8421 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 if (rep==NULL)
8423 return -1;
8424 else if (rep!=Py_None) {
8425 Py_DECREF(rep);
8426 break;
8427 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008428 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 }
8431 /* cache callback name lookup
8432 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008433 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008434 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008435
8436 switch (*error_handler) {
8437 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008438 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008439 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008440
8441 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008442 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 x = charmapencode_output('?', mapping, res, respos);
8444 if (x==enc_EXCEPTION) {
8445 return -1;
8446 }
8447 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008448 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 return -1;
8450 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008451 }
8452 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008453 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008454 *inpos = collendpos;
8455 break;
Victor Stinner50149202015-09-22 00:26:54 +02008456
8457 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008458 /* generate replacement (temporarily (mis)uses p) */
8459 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 char buffer[2+29+1+1];
8461 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008462 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 for (cp = buffer; *cp; ++cp) {
8464 x = charmapencode_output(*cp, mapping, res, respos);
8465 if (x==enc_EXCEPTION)
8466 return -1;
8467 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008468 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 return -1;
8470 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008471 }
8472 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008473 *inpos = collendpos;
8474 break;
Victor Stinner50149202015-09-22 00:26:54 +02008475
Benjamin Peterson14339b62009-01-31 16:36:08 +00008476 default:
Victor Stinner50149202015-09-22 00:26:54 +02008477 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008478 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008480 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008482 if (PyBytes_Check(repunicode)) {
8483 /* Directly copy bytes result to output. */
8484 Py_ssize_t outsize = PyBytes_Size(*res);
8485 Py_ssize_t requiredsize;
8486 repsize = PyBytes_Size(repunicode);
8487 requiredsize = *respos + repsize;
8488 if (requiredsize > outsize)
8489 /* Make room for all additional bytes. */
8490 if (charmapencode_resize(res, respos, requiredsize)) {
8491 Py_DECREF(repunicode);
8492 return -1;
8493 }
8494 memcpy(PyBytes_AsString(*res) + *respos,
8495 PyBytes_AsString(repunicode), repsize);
8496 *respos += repsize;
8497 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008498 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008499 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008500 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008501 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008502 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008503 Py_DECREF(repunicode);
8504 return -1;
8505 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008506 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008507 data = PyUnicode_DATA(repunicode);
8508 kind = PyUnicode_KIND(repunicode);
8509 for (index = 0; index < repsize; index++) {
8510 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8511 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008513 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008514 return -1;
8515 }
8516 else if (x==enc_FAILED) {
8517 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008518 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 return -1;
8520 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008521 }
8522 *inpos = newpos;
8523 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008524 }
8525 return 0;
8526}
8527
Alexander Belopolsky40018472011-02-26 01:02:56 +00008528PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008529_PyUnicode_EncodeCharmap(PyObject *unicode,
8530 PyObject *mapping,
8531 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 /* output object */
8534 PyObject *res = NULL;
8535 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008536 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008537 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008539 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008540 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008542 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008543 void *data;
8544 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008545
Benjamin Petersonbac79492012-01-14 13:34:47 -05008546 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008547 return NULL;
8548 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008549 data = PyUnicode_DATA(unicode);
8550 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008551
Guido van Rossumd57fd912000-03-10 22:53:23 +00008552 /* Default to Latin-1 */
8553 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008554 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 /* allocate enough for a simple encoding without
8557 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008558 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559 if (res == NULL)
8560 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008561 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008563
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008564 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008565 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008567 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 if (x==enc_EXCEPTION) /* error */
8569 goto onError;
8570 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008571 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008573 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 &res, &respos)) {
8575 goto onError;
8576 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008577 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 else
8579 /* done with this character => adjust input position */
8580 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008584 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008585 if (_PyBytes_Resize(&res, respos) < 0)
8586 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008587
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008589 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008590 return res;
8591
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 Py_XDECREF(res);
8594 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008595 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596 return NULL;
8597}
8598
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008599/* Deprecated */
8600PyObject *
8601PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8602 Py_ssize_t size,
8603 PyObject *mapping,
8604 const char *errors)
8605{
8606 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008607 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008608 if (unicode == NULL)
8609 return NULL;
8610 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8611 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008612 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008613}
8614
Alexander Belopolsky40018472011-02-26 01:02:56 +00008615PyObject *
8616PyUnicode_AsCharmapString(PyObject *unicode,
8617 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618{
8619 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 PyErr_BadArgument();
8621 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008622 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008623 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008624}
8625
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008627static void
8628make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008630 Py_ssize_t startpos, Py_ssize_t endpos,
8631 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008632{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 *exceptionObject = _PyUnicodeTranslateError_Create(
8635 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008636 }
8637 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8639 goto onError;
8640 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8641 goto onError;
8642 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8643 goto onError;
8644 return;
8645 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008646 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647 }
8648}
8649
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650/* error handling callback helper:
8651 build arguments, call the callback and check the arguments,
8652 put the result into newpos and return the replacement string, which
8653 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008654static PyObject *
8655unicode_translate_call_errorhandler(const char *errors,
8656 PyObject **errorHandler,
8657 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008659 Py_ssize_t startpos, Py_ssize_t endpos,
8660 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008662 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008663
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008664 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 PyObject *restuple;
8666 PyObject *resunicode;
8667
8668 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672 }
8673
8674 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008679 restuple = PyObject_CallFunctionObjArgs(
8680 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008681 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008684 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 Py_DECREF(restuple);
8686 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008688 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 &resunicode, &i_newpos)) {
8690 Py_DECREF(restuple);
8691 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008692 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008693 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008695 else
8696 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008698 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008699 Py_DECREF(restuple);
8700 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008701 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008702 Py_INCREF(resunicode);
8703 Py_DECREF(restuple);
8704 return resunicode;
8705}
8706
8707/* Lookup the character ch in the mapping and put the result in result,
8708 which must be decrefed by the caller.
8709 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008710static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008712{
Christian Heimes217cfd12007-12-02 14:31:20 +00008713 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714 PyObject *x;
8715
8716 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008718 x = PyObject_GetItem(mapping, w);
8719 Py_DECREF(w);
8720 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8722 /* No mapping found means: use 1:1 mapping. */
8723 PyErr_Clear();
8724 *result = NULL;
8725 return 0;
8726 } else
8727 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008728 }
8729 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 *result = x;
8731 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008732 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008733 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008735 if (value < 0 || value > MAX_UNICODE) {
8736 PyErr_Format(PyExc_ValueError,
8737 "character mapping must be in range(0x%x)",
8738 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 Py_DECREF(x);
8740 return -1;
8741 }
8742 *result = x;
8743 return 0;
8744 }
8745 else if (PyUnicode_Check(x)) {
8746 *result = x;
8747 return 0;
8748 }
8749 else {
8750 /* wrong return value */
8751 PyErr_SetString(PyExc_TypeError,
8752 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008753 Py_DECREF(x);
8754 return -1;
8755 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008756}
Victor Stinner1194ea02014-04-04 19:37:40 +02008757
8758/* lookup the character, write the result into the writer.
8759 Return 1 if the result was written into the writer, return 0 if the mapping
8760 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008761static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008762charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8763 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008764{
Victor Stinner1194ea02014-04-04 19:37:40 +02008765 PyObject *item;
8766
8767 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008769
8770 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008772 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008775 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008777
8778 if (item == Py_None) {
8779 Py_DECREF(item);
8780 return 0;
8781 }
8782
8783 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008784 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8785 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8786 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008787 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8788 Py_DECREF(item);
8789 return -1;
8790 }
8791 Py_DECREF(item);
8792 return 1;
8793 }
8794
8795 if (!PyUnicode_Check(item)) {
8796 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008798 }
8799
8800 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8801 Py_DECREF(item);
8802 return -1;
8803 }
8804
8805 Py_DECREF(item);
8806 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008807}
8808
Victor Stinner89a76ab2014-04-05 11:44:04 +02008809static int
8810unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8811 Py_UCS1 *translate)
8812{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008813 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008814 int ret = 0;
8815
Victor Stinner89a76ab2014-04-05 11:44:04 +02008816 if (charmaptranslate_lookup(ch, mapping, &item)) {
8817 return -1;
8818 }
8819
8820 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008821 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008822 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008823 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008824 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008825 /* not found => default to 1:1 mapping */
8826 translate[ch] = ch;
8827 return 1;
8828 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008829 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008830 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008831 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8832 used it */
8833 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834 /* invalid character or character outside ASCII:
8835 skip the fast translate */
8836 goto exit;
8837 }
8838 translate[ch] = (Py_UCS1)replace;
8839 }
8840 else if (PyUnicode_Check(item)) {
8841 Py_UCS4 replace;
8842
8843 if (PyUnicode_READY(item) == -1) {
8844 Py_DECREF(item);
8845 return -1;
8846 }
8847 if (PyUnicode_GET_LENGTH(item) != 1)
8848 goto exit;
8849
8850 replace = PyUnicode_READ_CHAR(item, 0);
8851 if (replace > 127)
8852 goto exit;
8853 translate[ch] = (Py_UCS1)replace;
8854 }
8855 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008856 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008857 goto exit;
8858 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859 ret = 1;
8860
Benjamin Peterson1365de72014-04-07 20:15:41 -04008861 exit:
8862 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863 return ret;
8864}
8865
8866/* Fast path for ascii => ascii translation. Return 1 if the whole string
8867 was translated into writer, return 0 if the input string was partially
8868 translated into writer, raise an exception and return -1 on error. */
8869static int
8870unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008871 _PyUnicodeWriter *writer, int ignore,
8872 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008873{
Victor Stinner872b2912014-04-05 14:27:07 +02008874 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008875 Py_ssize_t len;
8876 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008877 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878
Victor Stinner89a76ab2014-04-05 11:44:04 +02008879 len = PyUnicode_GET_LENGTH(input);
8880
Victor Stinner872b2912014-04-05 14:27:07 +02008881 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008882
8883 in = PyUnicode_1BYTE_DATA(input);
8884 end = in + len;
8885
8886 assert(PyUnicode_IS_ASCII(writer->buffer));
8887 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8888 out = PyUnicode_1BYTE_DATA(writer->buffer);
8889
Victor Stinner872b2912014-04-05 14:27:07 +02008890 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008891 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008892 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008893 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008894 int translate = unicode_fast_translate_lookup(mapping, ch,
8895 ascii_table);
8896 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008898 if (translate == 0)
8899 goto exit;
8900 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901 }
Victor Stinner872b2912014-04-05 14:27:07 +02008902 if (ch2 == 0xfe) {
8903 if (ignore)
8904 continue;
8905 goto exit;
8906 }
8907 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008908 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008909 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008910 }
Victor Stinner872b2912014-04-05 14:27:07 +02008911 res = 1;
8912
8913exit:
8914 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008915 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008916 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008917}
8918
Victor Stinner3222da22015-10-01 22:07:32 +02008919static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920_PyUnicode_TranslateCharmap(PyObject *input,
8921 PyObject *mapping,
8922 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008923{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008925 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926 Py_ssize_t size, i;
8927 int kind;
8928 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008929 _PyUnicodeWriter writer;
8930 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008931 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008932 PyObject *errorHandler = NULL;
8933 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008934 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008935 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008936
Guido van Rossumd57fd912000-03-10 22:53:23 +00008937 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 PyErr_BadArgument();
8939 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008940 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008942 if (PyUnicode_READY(input) == -1)
8943 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008944 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008945 kind = PyUnicode_KIND(input);
8946 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008947
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008948 if (size == 0)
8949 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008951 /* allocate enough for a simple 1:1 translation without
8952 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008953 _PyUnicodeWriter_Init(&writer);
8954 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008956
Victor Stinner872b2912014-04-05 14:27:07 +02008957 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8958
Victor Stinner33798672016-03-01 21:59:58 +01008959 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008960 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008961 if (PyUnicode_IS_ASCII(input)) {
8962 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8963 if (res < 0) {
8964 _PyUnicodeWriter_Dealloc(&writer);
8965 return NULL;
8966 }
8967 if (res == 1)
8968 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008969 }
Victor Stinner33798672016-03-01 21:59:58 +01008970 else {
8971 i = 0;
8972 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008974 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008976 int translate;
8977 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8978 Py_ssize_t newpos;
8979 /* startpos for collecting untranslatable chars */
8980 Py_ssize_t collstart;
8981 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008983
Victor Stinner1194ea02014-04-04 19:37:40 +02008984 ch = PyUnicode_READ(kind, data, i);
8985 translate = charmaptranslate_output(ch, mapping, &writer);
8986 if (translate < 0)
8987 goto onError;
8988
8989 if (translate != 0) {
8990 /* it worked => adjust input pointer */
8991 ++i;
8992 continue;
8993 }
8994
8995 /* untranslatable character */
8996 collstart = i;
8997 collend = i+1;
8998
8999 /* find all untranslatable characters */
9000 while (collend < size) {
9001 PyObject *x;
9002 ch = PyUnicode_READ(kind, data, collend);
9003 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009004 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009005 Py_XDECREF(x);
9006 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009007 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009008 ++collend;
9009 }
9010
9011 if (ignore) {
9012 i = collend;
9013 }
9014 else {
9015 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9016 reason, input, &exc,
9017 collstart, collend, &newpos);
9018 if (repunicode == NULL)
9019 goto onError;
9020 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009021 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009022 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009023 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009024 Py_DECREF(repunicode);
9025 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009026 }
9027 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009028 Py_XDECREF(exc);
9029 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009030 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031
Benjamin Peterson29060642009-01-31 22:14:21 +00009032 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009033 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009034 Py_XDECREF(exc);
9035 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036 return NULL;
9037}
9038
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009039/* Deprecated. Use PyUnicode_Translate instead. */
9040PyObject *
9041PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9042 Py_ssize_t size,
9043 PyObject *mapping,
9044 const char *errors)
9045{
Christian Heimes5f520f42012-09-11 14:03:25 +02009046 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009047 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009048 if (!unicode)
9049 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009050 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9051 Py_DECREF(unicode);
9052 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053}
9054
Alexander Belopolsky40018472011-02-26 01:02:56 +00009055PyObject *
9056PyUnicode_Translate(PyObject *str,
9057 PyObject *mapping,
9058 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009059{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009060 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009061 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009062 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009063}
Tim Petersced69f82003-09-16 20:30:58 +00009064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009065PyObject *
9066_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9067{
9068 if (!PyUnicode_Check(unicode)) {
9069 PyErr_BadInternalCall();
9070 return NULL;
9071 }
9072 if (PyUnicode_READY(unicode) == -1)
9073 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009074 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009075 /* If the string is already ASCII, just return the same string */
9076 Py_INCREF(unicode);
9077 return unicode;
9078 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009079
9080 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9081 PyObject *result = PyUnicode_New(len, 127);
9082 if (result == NULL) {
9083 return NULL;
9084 }
9085
9086 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9087 int kind = PyUnicode_KIND(unicode);
9088 const void *data = PyUnicode_DATA(unicode);
9089 Py_ssize_t i;
9090 for (i = 0; i < len; ++i) {
9091 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9092 if (ch < 127) {
9093 out[i] = ch;
9094 }
9095 else if (Py_UNICODE_ISSPACE(ch)) {
9096 out[i] = ' ';
9097 }
9098 else {
9099 int decimal = Py_UNICODE_TODECIMAL(ch);
9100 if (decimal < 0) {
9101 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009102 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009103 _PyUnicode_LENGTH(result) = i + 1;
9104 break;
9105 }
9106 out[i] = '0' + decimal;
9107 }
9108 }
9109
INADA Naoki16dfca42018-07-14 12:06:43 +09009110 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009111 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112}
9113
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009114PyObject *
9115PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9116 Py_ssize_t length)
9117{
Victor Stinnerf0124502011-11-21 23:12:56 +01009118 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009119 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009120 Py_UCS4 maxchar;
9121 enum PyUnicode_Kind kind;
9122 void *data;
9123
Victor Stinner99d7ad02012-02-22 13:37:39 +01009124 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009125 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009126 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009127 if (ch > 127) {
9128 int decimal = Py_UNICODE_TODECIMAL(ch);
9129 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009130 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009131 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009132 }
9133 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009134
9135 /* Copy to a new string */
9136 decimal = PyUnicode_New(length, maxchar);
9137 if (decimal == NULL)
9138 return decimal;
9139 kind = PyUnicode_KIND(decimal);
9140 data = PyUnicode_DATA(decimal);
9141 /* Iterate over code points */
9142 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009143 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009144 if (ch > 127) {
9145 int decimal = Py_UNICODE_TODECIMAL(ch);
9146 if (decimal >= 0)
9147 ch = '0' + decimal;
9148 }
9149 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009150 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009151 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009152}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009153/* --- Decimal Encoder ---------------------------------------------------- */
9154
Alexander Belopolsky40018472011-02-26 01:02:56 +00009155int
9156PyUnicode_EncodeDecimal(Py_UNICODE *s,
9157 Py_ssize_t length,
9158 char *output,
9159 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009160{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009161 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009162 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009163 enum PyUnicode_Kind kind;
9164 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009165
9166 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 PyErr_BadArgument();
9168 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009169 }
9170
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009171 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009172 if (unicode == NULL)
9173 return -1;
9174
Victor Stinner42bf7752011-11-21 22:52:58 +01009175 kind = PyUnicode_KIND(unicode);
9176 data = PyUnicode_DATA(unicode);
9177
Victor Stinnerb84d7232011-11-22 01:50:07 +01009178 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009179 PyObject *exc;
9180 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009181 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009182 Py_ssize_t startpos;
9183
9184 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009185
Benjamin Peterson29060642009-01-31 22:14:21 +00009186 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009187 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009188 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009189 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009190 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009191 decimal = Py_UNICODE_TODECIMAL(ch);
9192 if (decimal >= 0) {
9193 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009194 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009195 continue;
9196 }
9197 if (0 < ch && ch < 256) {
9198 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009199 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009200 continue;
9201 }
Victor Stinner6345be92011-11-25 20:09:01 +01009202
Victor Stinner42bf7752011-11-21 22:52:58 +01009203 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009204 exc = NULL;
9205 raise_encode_exception(&exc, "decimal", unicode,
9206 startpos, startpos+1,
9207 "invalid decimal Unicode string");
9208 Py_XDECREF(exc);
9209 Py_DECREF(unicode);
9210 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009211 }
9212 /* 0-terminate the output string */
9213 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009214 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009215 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009216}
9217
Guido van Rossumd57fd912000-03-10 22:53:23 +00009218/* --- Helpers ------------------------------------------------------------ */
9219
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009220/* helper macro to fixup start/end slice values */
9221#define ADJUST_INDICES(start, end, len) \
9222 if (end > len) \
9223 end = len; \
9224 else if (end < 0) { \
9225 end += len; \
9226 if (end < 0) \
9227 end = 0; \
9228 } \
9229 if (start < 0) { \
9230 start += len; \
9231 if (start < 0) \
9232 start = 0; \
9233 }
9234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009236any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009238 Py_ssize_t end,
9239 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009240{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009241 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009242 void *buf1, *buf2;
9243 Py_ssize_t len1, len2, result;
9244
9245 kind1 = PyUnicode_KIND(s1);
9246 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009247 if (kind1 < kind2)
9248 return -1;
9249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009250 len1 = PyUnicode_GET_LENGTH(s1);
9251 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009252 ADJUST_INDICES(start, end, len1);
9253 if (end - start < len2)
9254 return -1;
9255
9256 buf1 = PyUnicode_DATA(s1);
9257 buf2 = PyUnicode_DATA(s2);
9258 if (len2 == 1) {
9259 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9260 result = findchar((const char *)buf1 + kind1*start,
9261 kind1, end - start, ch, direction);
9262 if (result == -1)
9263 return -1;
9264 else
9265 return start + result;
9266 }
9267
9268 if (kind2 != kind1) {
9269 buf2 = _PyUnicode_AsKind(s2, kind1);
9270 if (!buf2)
9271 return -2;
9272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273
Victor Stinner794d5672011-10-10 03:21:36 +02009274 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009275 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009276 case PyUnicode_1BYTE_KIND:
9277 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9278 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9279 else
9280 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9281 break;
9282 case PyUnicode_2BYTE_KIND:
9283 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9284 break;
9285 case PyUnicode_4BYTE_KIND:
9286 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9287 break;
9288 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009289 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009290 }
9291 }
9292 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009293 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009294 case PyUnicode_1BYTE_KIND:
9295 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9296 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9297 else
9298 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9299 break;
9300 case PyUnicode_2BYTE_KIND:
9301 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9302 break;
9303 case PyUnicode_4BYTE_KIND:
9304 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9305 break;
9306 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009307 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009309 }
9310
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009311 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 PyMem_Free(buf2);
9313
9314 return result;
9315}
9316
9317Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009318_PyUnicode_InsertThousandsGrouping(
9319 PyObject *unicode, Py_ssize_t index,
9320 Py_ssize_t n_buffer,
9321 void *digits, Py_ssize_t n_digits,
9322 Py_ssize_t min_width,
9323 const char *grouping, PyObject *thousands_sep,
9324 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325{
Victor Stinner41a863c2012-02-24 00:37:51 +01009326 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009327 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009328 Py_ssize_t thousands_sep_len;
9329 Py_ssize_t len;
9330
9331 if (unicode != NULL) {
9332 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009333 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009334 }
9335 else {
9336 kind = PyUnicode_1BYTE_KIND;
9337 data = NULL;
9338 }
9339 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9340 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9341 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9342 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009343 if (thousands_sep_kind < kind) {
9344 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9345 if (!thousands_sep_data)
9346 return -1;
9347 }
9348 else {
9349 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9350 if (!data)
9351 return -1;
9352 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009353 }
9354
Benjamin Petersonead6b532011-12-20 17:23:42 -06009355 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009357 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009358 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009359 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009360 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009361 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009362 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009363 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009364 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009365 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009366 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009367 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009369 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009370 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009371 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009372 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009373 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009374 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009375 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009376 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009377 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009378 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009379 break;
9380 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009381 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009383 if (unicode != NULL && thousands_sep_kind != kind) {
9384 if (thousands_sep_kind < kind)
9385 PyMem_Free(thousands_sep_data);
9386 else
9387 PyMem_Free(data);
9388 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009389 if (unicode == NULL) {
9390 *maxchar = 127;
9391 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009392 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009393 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009394 }
9395 }
9396 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397}
9398
9399
Alexander Belopolsky40018472011-02-26 01:02:56 +00009400Py_ssize_t
9401PyUnicode_Count(PyObject *str,
9402 PyObject *substr,
9403 Py_ssize_t start,
9404 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009405{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009406 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009407 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408 void *buf1 = NULL, *buf2 = NULL;
9409 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009410
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009411 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009412 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009413
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009414 kind1 = PyUnicode_KIND(str);
9415 kind2 = PyUnicode_KIND(substr);
9416 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009417 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009418
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009419 len1 = PyUnicode_GET_LENGTH(str);
9420 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009422 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009423 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009424
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009425 buf1 = PyUnicode_DATA(str);
9426 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009427 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009428 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009429 if (!buf2)
9430 goto onError;
9431 }
9432
9433 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009435 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009436 result = asciilib_count(
9437 ((Py_UCS1*)buf1) + start, end - start,
9438 buf2, len2, PY_SSIZE_T_MAX
9439 );
9440 else
9441 result = ucs1lib_count(
9442 ((Py_UCS1*)buf1) + start, end - start,
9443 buf2, len2, PY_SSIZE_T_MAX
9444 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 break;
9446 case PyUnicode_2BYTE_KIND:
9447 result = ucs2lib_count(
9448 ((Py_UCS2*)buf1) + start, end - start,
9449 buf2, len2, PY_SSIZE_T_MAX
9450 );
9451 break;
9452 case PyUnicode_4BYTE_KIND:
9453 result = ucs4lib_count(
9454 ((Py_UCS4*)buf1) + start, end - start,
9455 buf2, len2, PY_SSIZE_T_MAX
9456 );
9457 break;
9458 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009459 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009461
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009462 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 PyMem_Free(buf2);
9464
Guido van Rossumd57fd912000-03-10 22:53:23 +00009465 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009467 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 PyMem_Free(buf2);
9469 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470}
9471
Alexander Belopolsky40018472011-02-26 01:02:56 +00009472Py_ssize_t
9473PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009474 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009475 Py_ssize_t start,
9476 Py_ssize_t end,
9477 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009479 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009480 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009481
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009482 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483}
9484
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485Py_ssize_t
9486PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9487 Py_ssize_t start, Py_ssize_t end,
9488 int direction)
9489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009491 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 if (PyUnicode_READY(str) == -1)
9493 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009494 len = PyUnicode_GET_LENGTH(str);
9495 ADJUST_INDICES(start, end, len);
9496 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009497 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009499 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9500 kind, end-start, ch, direction);
9501 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009503 else
9504 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505}
9506
Alexander Belopolsky40018472011-02-26 01:02:56 +00009507static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009508tailmatch(PyObject *self,
9509 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009510 Py_ssize_t start,
9511 Py_ssize_t end,
9512 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 int kind_self;
9515 int kind_sub;
9516 void *data_self;
9517 void *data_sub;
9518 Py_ssize_t offset;
9519 Py_ssize_t i;
9520 Py_ssize_t end_sub;
9521
9522 if (PyUnicode_READY(self) == -1 ||
9523 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009524 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9527 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009528 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009529 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009531 if (PyUnicode_GET_LENGTH(substring) == 0)
9532 return 1;
9533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 kind_self = PyUnicode_KIND(self);
9535 data_self = PyUnicode_DATA(self);
9536 kind_sub = PyUnicode_KIND(substring);
9537 data_sub = PyUnicode_DATA(substring);
9538 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9539
9540 if (direction > 0)
9541 offset = end;
9542 else
9543 offset = start;
9544
9545 if (PyUnicode_READ(kind_self, data_self, offset) ==
9546 PyUnicode_READ(kind_sub, data_sub, 0) &&
9547 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9548 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9549 /* If both are of the same kind, memcmp is sufficient */
9550 if (kind_self == kind_sub) {
9551 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009552 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 data_sub,
9554 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009555 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009557 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 else {
9559 /* We do not need to compare 0 and len(substring)-1 because
9560 the if statement above ensured already that they are equal
9561 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 for (i = 1; i < end_sub; ++i) {
9563 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9564 PyUnicode_READ(kind_sub, data_sub, i))
9565 return 0;
9566 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009569 }
9570
9571 return 0;
9572}
9573
Alexander Belopolsky40018472011-02-26 01:02:56 +00009574Py_ssize_t
9575PyUnicode_Tailmatch(PyObject *str,
9576 PyObject *substr,
9577 Py_ssize_t start,
9578 Py_ssize_t end,
9579 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009580{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009581 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009582 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009583
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009584 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585}
9586
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009587static PyObject *
9588ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009590 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9591 char *resdata, *data = PyUnicode_DATA(self);
9592 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009593
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009594 res = PyUnicode_New(len, 127);
9595 if (res == NULL)
9596 return NULL;
9597 resdata = PyUnicode_DATA(res);
9598 if (lower)
9599 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009601 _Py_bytes_upper(resdata, data, len);
9602 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009603}
9604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009606handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009607{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009608 Py_ssize_t j;
9609 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009610 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009612
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009613 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9614
9615 where ! is a negation and \p{xxx} is a character with property xxx.
9616 */
9617 for (j = i - 1; j >= 0; j--) {
9618 c = PyUnicode_READ(kind, data, j);
9619 if (!_PyUnicode_IsCaseIgnorable(c))
9620 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009622 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9623 if (final_sigma) {
9624 for (j = i + 1; j < length; j++) {
9625 c = PyUnicode_READ(kind, data, j);
9626 if (!_PyUnicode_IsCaseIgnorable(c))
9627 break;
9628 }
9629 final_sigma = j == length || !_PyUnicode_IsCased(c);
9630 }
9631 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632}
9633
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009634static int
9635lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9636 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009637{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638 /* Obscure special case. */
9639 if (c == 0x3A3) {
9640 mapped[0] = handle_capital_sigma(kind, data, length, i);
9641 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009644}
9645
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009646static Py_ssize_t
9647do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 Py_ssize_t i, k = 0;
9650 int n_res, j;
9651 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009652
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009653 c = PyUnicode_READ(kind, data, 0);
9654 n_res = _PyUnicode_ToUpperFull(c, mapped);
9655 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009656 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009657 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659 for (i = 1; i < length; i++) {
9660 c = PyUnicode_READ(kind, data, i);
9661 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9662 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009663 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009664 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009665 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009666 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668}
9669
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670static Py_ssize_t
9671do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9672 Py_ssize_t i, k = 0;
9673
9674 for (i = 0; i < length; i++) {
9675 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9676 int n_res, j;
9677 if (Py_UNICODE_ISUPPER(c)) {
9678 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9679 }
9680 else if (Py_UNICODE_ISLOWER(c)) {
9681 n_res = _PyUnicode_ToUpperFull(c, mapped);
9682 }
9683 else {
9684 n_res = 1;
9685 mapped[0] = c;
9686 }
9687 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009688 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009689 res[k++] = mapped[j];
9690 }
9691 }
9692 return k;
9693}
9694
9695static Py_ssize_t
9696do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9697 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009698{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009699 Py_ssize_t i, k = 0;
9700
9701 for (i = 0; i < length; i++) {
9702 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9703 int n_res, j;
9704 if (lower)
9705 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9706 else
9707 n_res = _PyUnicode_ToUpperFull(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 Petersonb2bf01d2012-01-11 18:17:06 -05009710 res[k++] = mapped[j];
9711 }
9712 }
9713 return k;
9714}
9715
9716static Py_ssize_t
9717do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9718{
9719 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9720}
9721
9722static Py_ssize_t
9723do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9724{
9725 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9726}
9727
Benjamin Petersone51757f2012-01-12 21:10:29 -05009728static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009729do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9730{
9731 Py_ssize_t i, k = 0;
9732
9733 for (i = 0; i < length; i++) {
9734 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9735 Py_UCS4 mapped[3];
9736 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9737 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009738 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009739 res[k++] = mapped[j];
9740 }
9741 }
9742 return k;
9743}
9744
9745static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009746do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9747{
9748 Py_ssize_t i, k = 0;
9749 int previous_is_cased;
9750
9751 previous_is_cased = 0;
9752 for (i = 0; i < length; i++) {
9753 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9754 Py_UCS4 mapped[3];
9755 int n_res, j;
9756
9757 if (previous_is_cased)
9758 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9759 else
9760 n_res = _PyUnicode_ToTitleFull(c, mapped);
9761
9762 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009763 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009764 res[k++] = mapped[j];
9765 }
9766
9767 previous_is_cased = _PyUnicode_IsCased(c);
9768 }
9769 return k;
9770}
9771
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009772static PyObject *
9773case_operation(PyObject *self,
9774 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9775{
9776 PyObject *res = NULL;
9777 Py_ssize_t length, newlength = 0;
9778 int kind, outkind;
9779 void *data, *outdata;
9780 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9781
Benjamin Petersoneea48462012-01-16 14:28:50 -05009782 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009783
9784 kind = PyUnicode_KIND(self);
9785 data = PyUnicode_DATA(self);
9786 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009787 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009788 PyErr_SetString(PyExc_OverflowError, "string is too long");
9789 return NULL;
9790 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009791 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009792 if (tmp == NULL)
9793 return PyErr_NoMemory();
9794 newlength = perform(kind, data, length, tmp, &maxchar);
9795 res = PyUnicode_New(newlength, maxchar);
9796 if (res == NULL)
9797 goto leave;
9798 tmpend = tmp + newlength;
9799 outdata = PyUnicode_DATA(res);
9800 outkind = PyUnicode_KIND(res);
9801 switch (outkind) {
9802 case PyUnicode_1BYTE_KIND:
9803 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9804 break;
9805 case PyUnicode_2BYTE_KIND:
9806 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9807 break;
9808 case PyUnicode_4BYTE_KIND:
9809 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9810 break;
9811 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009812 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009813 }
9814 leave:
9815 PyMem_FREE(tmp);
9816 return res;
9817}
9818
Tim Peters8ce9f162004-08-27 01:49:32 +00009819PyObject *
9820PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009821{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009822 PyObject *res;
9823 PyObject *fseq;
9824 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009825 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009826
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009827 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009828 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009829 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009830 }
9831
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009832 /* NOTE: the following code can't call back into Python code,
9833 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009834 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009835
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009836 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009837 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009838 res = _PyUnicode_JoinArray(separator, items, seqlen);
9839 Py_DECREF(fseq);
9840 return res;
9841}
9842
9843PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009844_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009845{
9846 PyObject *res = NULL; /* the result */
9847 PyObject *sep = NULL;
9848 Py_ssize_t seplen;
9849 PyObject *item;
9850 Py_ssize_t sz, i, res_offset;
9851 Py_UCS4 maxchar;
9852 Py_UCS4 item_maxchar;
9853 int use_memcpy;
9854 unsigned char *res_data = NULL, *sep_data = NULL;
9855 PyObject *last_obj;
9856 unsigned int kind = 0;
9857
Tim Peters05eba1f2004-08-27 21:32:02 +00009858 /* If empty sequence, return u"". */
9859 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009860 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009861 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009862
Tim Peters05eba1f2004-08-27 21:32:02 +00009863 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009864 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009865 if (seqlen == 1) {
9866 if (PyUnicode_CheckExact(items[0])) {
9867 res = items[0];
9868 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009869 return res;
9870 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009871 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009872 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009873 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009874 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009875 /* Set up sep and seplen */
9876 if (separator == NULL) {
9877 /* fall back to a blank space separator */
9878 sep = PyUnicode_FromOrdinal(' ');
9879 if (!sep)
9880 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009881 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009882 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009883 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009884 else {
9885 if (!PyUnicode_Check(separator)) {
9886 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009887 "separator: expected str instance,"
9888 " %.80s found",
9889 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +02009890 goto onError;
9891 }
9892 if (PyUnicode_READY(separator))
9893 goto onError;
9894 sep = separator;
9895 seplen = PyUnicode_GET_LENGTH(separator);
9896 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9897 /* inc refcount to keep this code path symmetric with the
9898 above case of a blank separator */
9899 Py_INCREF(sep);
9900 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009901 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009902 }
9903
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009904 /* There are at least two things to join, or else we have a subclass
9905 * of str in the sequence.
9906 * Do a pre-pass to figure out the total amount of space we'll
9907 * need (sz), and see whether all argument are strings.
9908 */
9909 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009910#ifdef Py_DEBUG
9911 use_memcpy = 0;
9912#else
9913 use_memcpy = 1;
9914#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009915 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009916 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009917 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009918 if (!PyUnicode_Check(item)) {
9919 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009920 "sequence item %zd: expected str instance,"
9921 " %.80s found",
9922 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009923 goto onError;
9924 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925 if (PyUnicode_READY(item) == -1)
9926 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009927 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009929 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009930 if (i != 0) {
9931 add_sz += seplen;
9932 }
9933 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009934 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009935 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009936 goto onError;
9937 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009938 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009939 if (use_memcpy && last_obj != NULL) {
9940 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9941 use_memcpy = 0;
9942 }
9943 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009944 }
Tim Petersced69f82003-09-16 20:30:58 +00009945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009947 if (res == NULL)
9948 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009949
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009950 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009951#ifdef Py_DEBUG
9952 use_memcpy = 0;
9953#else
9954 if (use_memcpy) {
9955 res_data = PyUnicode_1BYTE_DATA(res);
9956 kind = PyUnicode_KIND(res);
9957 if (seplen != 0)
9958 sep_data = PyUnicode_1BYTE_DATA(sep);
9959 }
9960#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009961 if (use_memcpy) {
9962 for (i = 0; i < seqlen; ++i) {
9963 Py_ssize_t itemlen;
9964 item = items[i];
9965
9966 /* Copy item, and maybe the separator. */
9967 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009968 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009969 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009970 kind * seplen);
9971 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009972 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009973
9974 itemlen = PyUnicode_GET_LENGTH(item);
9975 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009976 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009977 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009978 kind * itemlen);
9979 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009980 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009981 }
9982 assert(res_data == PyUnicode_1BYTE_DATA(res)
9983 + kind * PyUnicode_GET_LENGTH(res));
9984 }
9985 else {
9986 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9987 Py_ssize_t itemlen;
9988 item = items[i];
9989
9990 /* Copy item, and maybe the separator. */
9991 if (i && seplen != 0) {
9992 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9993 res_offset += seplen;
9994 }
9995
9996 itemlen = PyUnicode_GET_LENGTH(item);
9997 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009998 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009999 res_offset += itemlen;
10000 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010001 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010002 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010003 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010006 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010007 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008
Benjamin Peterson29060642009-01-31 22:14:21 +000010009 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010011 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010012 return NULL;
10013}
10014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015#define FILL(kind, data, value, start, length) \
10016 do { \
10017 Py_ssize_t i_ = 0; \
10018 assert(kind != PyUnicode_WCHAR_KIND); \
10019 switch ((kind)) { \
10020 case PyUnicode_1BYTE_KIND: { \
10021 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010022 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023 break; \
10024 } \
10025 case PyUnicode_2BYTE_KIND: { \
10026 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10027 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10028 break; \
10029 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010030 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10032 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10033 break; \
10034 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010035 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 } \
10037 } while (0)
10038
Victor Stinnerd3f08822012-05-29 12:57:52 +020010039void
10040_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10041 Py_UCS4 fill_char)
10042{
10043 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10044 const void *data = PyUnicode_DATA(unicode);
10045 assert(PyUnicode_IS_READY(unicode));
10046 assert(unicode_modifiable(unicode));
10047 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10048 assert(start >= 0);
10049 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10050 FILL(kind, data, fill_char, start, length);
10051}
10052
Victor Stinner3fe55312012-01-04 00:33:50 +010010053Py_ssize_t
10054PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10055 Py_UCS4 fill_char)
10056{
10057 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010058
10059 if (!PyUnicode_Check(unicode)) {
10060 PyErr_BadInternalCall();
10061 return -1;
10062 }
10063 if (PyUnicode_READY(unicode) == -1)
10064 return -1;
10065 if (unicode_check_modifiable(unicode))
10066 return -1;
10067
Victor Stinnerd3f08822012-05-29 12:57:52 +020010068 if (start < 0) {
10069 PyErr_SetString(PyExc_IndexError, "string index out of range");
10070 return -1;
10071 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010072 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10073 PyErr_SetString(PyExc_ValueError,
10074 "fill character is bigger than "
10075 "the string maximum character");
10076 return -1;
10077 }
10078
10079 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10080 length = Py_MIN(maxlen, length);
10081 if (length <= 0)
10082 return 0;
10083
Victor Stinnerd3f08822012-05-29 12:57:52 +020010084 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010085 return length;
10086}
10087
Victor Stinner9310abb2011-10-05 00:59:23 +020010088static PyObject *
10089pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010090 Py_ssize_t left,
10091 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 PyObject *u;
10095 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010096 int kind;
10097 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010098
10099 if (left < 0)
10100 left = 0;
10101 if (right < 0)
10102 right = 0;
10103
Victor Stinnerc4b49542011-12-11 22:44:26 +010010104 if (left == 0 && right == 0)
10105 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10108 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010109 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10110 return NULL;
10111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010113 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010115 if (!u)
10116 return NULL;
10117
10118 kind = PyUnicode_KIND(u);
10119 data = PyUnicode_DATA(u);
10120 if (left)
10121 FILL(kind, data, fill, 0, left);
10122 if (right)
10123 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010124 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010125 assert(_PyUnicode_CheckConsistency(u, 1));
10126 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010127}
10128
Alexander Belopolsky40018472011-02-26 01:02:56 +000010129PyObject *
10130PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010131{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010134 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010136
Benjamin Petersonead6b532011-12-20 17:23:42 -060010137 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010139 if (PyUnicode_IS_ASCII(string))
10140 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010141 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010142 PyUnicode_GET_LENGTH(string), keepends);
10143 else
10144 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010145 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010146 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 break;
10148 case PyUnicode_2BYTE_KIND:
10149 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010150 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 PyUnicode_GET_LENGTH(string), keepends);
10152 break;
10153 case PyUnicode_4BYTE_KIND:
10154 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010155 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 PyUnicode_GET_LENGTH(string), keepends);
10157 break;
10158 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010159 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010161 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162}
10163
Alexander Belopolsky40018472011-02-26 01:02:56 +000010164static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010165split(PyObject *self,
10166 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010167 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010169 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 void *buf1, *buf2;
10171 Py_ssize_t len1, len2;
10172 PyObject* out;
10173
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010175 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (PyUnicode_READY(self) == -1)
10178 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010181 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 if (PyUnicode_IS_ASCII(self))
10184 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010185 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186 PyUnicode_GET_LENGTH(self), maxcount
10187 );
10188 else
10189 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010190 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 PyUnicode_GET_LENGTH(self), maxcount
10192 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 case PyUnicode_2BYTE_KIND:
10194 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 PyUnicode_GET_LENGTH(self), maxcount
10197 );
10198 case PyUnicode_4BYTE_KIND:
10199 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010200 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 PyUnicode_GET_LENGTH(self), maxcount
10202 );
10203 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010204 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 }
10206
10207 if (PyUnicode_READY(substring) == -1)
10208 return NULL;
10209
10210 kind1 = PyUnicode_KIND(self);
10211 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 len1 = PyUnicode_GET_LENGTH(self);
10213 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010214 if (kind1 < kind2 || len1 < len2) {
10215 out = PyList_New(1);
10216 if (out == NULL)
10217 return NULL;
10218 Py_INCREF(self);
10219 PyList_SET_ITEM(out, 0, self);
10220 return out;
10221 }
10222 buf1 = PyUnicode_DATA(self);
10223 buf2 = PyUnicode_DATA(substring);
10224 if (kind2 != kind1) {
10225 buf2 = _PyUnicode_AsKind(substring, kind1);
10226 if (!buf2)
10227 return NULL;
10228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010230 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010232 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10233 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235 else
10236 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010237 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 break;
10239 case PyUnicode_2BYTE_KIND:
10240 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010241 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 break;
10243 case PyUnicode_4BYTE_KIND:
10244 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010245 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 break;
10247 default:
10248 out = NULL;
10249 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010250 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 PyMem_Free(buf2);
10252 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010253}
10254
Alexander Belopolsky40018472011-02-26 01:02:56 +000010255static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010256rsplit(PyObject *self,
10257 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010258 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010259{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010260 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 void *buf1, *buf2;
10262 Py_ssize_t len1, len2;
10263 PyObject* out;
10264
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010265 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010266 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 if (PyUnicode_READY(self) == -1)
10269 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010272 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 if (PyUnicode_IS_ASCII(self))
10275 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010277 PyUnicode_GET_LENGTH(self), maxcount
10278 );
10279 else
10280 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010281 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010282 PyUnicode_GET_LENGTH(self), maxcount
10283 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 case PyUnicode_2BYTE_KIND:
10285 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010286 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 PyUnicode_GET_LENGTH(self), maxcount
10288 );
10289 case PyUnicode_4BYTE_KIND:
10290 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010291 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 PyUnicode_GET_LENGTH(self), maxcount
10293 );
10294 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010295 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 }
10297
10298 if (PyUnicode_READY(substring) == -1)
10299 return NULL;
10300
10301 kind1 = PyUnicode_KIND(self);
10302 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 len1 = PyUnicode_GET_LENGTH(self);
10304 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010305 if (kind1 < kind2 || len1 < len2) {
10306 out = PyList_New(1);
10307 if (out == NULL)
10308 return NULL;
10309 Py_INCREF(self);
10310 PyList_SET_ITEM(out, 0, self);
10311 return out;
10312 }
10313 buf1 = PyUnicode_DATA(self);
10314 buf2 = PyUnicode_DATA(substring);
10315 if (kind2 != kind1) {
10316 buf2 = _PyUnicode_AsKind(substring, kind1);
10317 if (!buf2)
10318 return NULL;
10319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010321 switch (kind1) {
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(self) && PyUnicode_IS_ASCII(substring))
10324 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010325 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326 else
10327 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010328 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 break;
10330 case PyUnicode_2BYTE_KIND:
10331 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010332 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 break;
10334 case PyUnicode_4BYTE_KIND:
10335 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010336 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 break;
10338 default:
10339 out = NULL;
10340 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010341 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 PyMem_Free(buf2);
10343 return out;
10344}
10345
10346static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010347anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10348 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010350 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010352 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10353 return asciilib_find(buf1, len1, buf2, len2, offset);
10354 else
10355 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 case PyUnicode_2BYTE_KIND:
10357 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10358 case PyUnicode_4BYTE_KIND:
10359 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10360 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010361 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362}
10363
10364static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010365anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10366 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010368 switch (kind) {
10369 case PyUnicode_1BYTE_KIND:
10370 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10371 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10372 else
10373 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10374 case PyUnicode_2BYTE_KIND:
10375 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10376 case PyUnicode_4BYTE_KIND:
10377 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10378 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010379 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010380}
10381
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010382static void
10383replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10384 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10385{
10386 int kind = PyUnicode_KIND(u);
10387 void *data = PyUnicode_DATA(u);
10388 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10389 if (kind == PyUnicode_1BYTE_KIND) {
10390 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10391 (Py_UCS1 *)data + len,
10392 u1, u2, maxcount);
10393 }
10394 else if (kind == PyUnicode_2BYTE_KIND) {
10395 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10396 (Py_UCS2 *)data + len,
10397 u1, u2, maxcount);
10398 }
10399 else {
10400 assert(kind == PyUnicode_4BYTE_KIND);
10401 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10402 (Py_UCS4 *)data + len,
10403 u1, u2, maxcount);
10404 }
10405}
10406
Alexander Belopolsky40018472011-02-26 01:02:56 +000010407static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408replace(PyObject *self, PyObject *str1,
10409 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 PyObject *u;
10412 char *sbuf = PyUnicode_DATA(self);
10413 char *buf1 = PyUnicode_DATA(str1);
10414 char *buf2 = PyUnicode_DATA(str2);
10415 int srelease = 0, release1 = 0, release2 = 0;
10416 int skind = PyUnicode_KIND(self);
10417 int kind1 = PyUnicode_KIND(str1);
10418 int kind2 = PyUnicode_KIND(str2);
10419 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10420 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10421 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010422 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010423 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010424
10425 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010426 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010428 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429
Victor Stinner59de0ee2011-10-07 10:01:28 +020010430 if (str1 == str2)
10431 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432
Victor Stinner49a0a212011-10-12 23:46:10 +020010433 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010434 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10435 if (maxchar < maxchar_str1)
10436 /* substring too wide to be present */
10437 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10439 /* Replacing str1 with str2 may cause a maxchar reduction in the
10440 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010441 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010442 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010445 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010447 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010449 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010450 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010451 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010452
Victor Stinner69ed0f42013-04-09 21:48:24 +020010453 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010454 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010455 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010456 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010457 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010459 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010461
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010462 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10463 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010464 }
10465 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 int rkind = skind;
10467 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010468 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 if (kind1 < rkind) {
10471 /* widen substring */
10472 buf1 = _PyUnicode_AsKind(str1, rkind);
10473 if (!buf1) goto error;
10474 release1 = 1;
10475 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010476 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010477 if (i < 0)
10478 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 if (rkind > kind2) {
10480 /* widen replacement */
10481 buf2 = _PyUnicode_AsKind(str2, rkind);
10482 if (!buf2) goto error;
10483 release2 = 1;
10484 }
10485 else if (rkind < kind2) {
10486 /* widen self and buf1 */
10487 rkind = kind2;
10488 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010489 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 sbuf = _PyUnicode_AsKind(self, rkind);
10491 if (!sbuf) goto error;
10492 srelease = 1;
10493 buf1 = _PyUnicode_AsKind(str1, rkind);
10494 if (!buf1) goto error;
10495 release1 = 1;
10496 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010497 u = PyUnicode_New(slen, maxchar);
10498 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010500 assert(PyUnicode_KIND(u) == rkind);
10501 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010502
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010503 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010504 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010505 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010507 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010509
10510 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010511 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010512 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010513 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010514 if (i == -1)
10515 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010516 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010518 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010520 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010521 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010522 }
10523 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010525 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010526 int rkind = skind;
10527 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010530 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 buf1 = _PyUnicode_AsKind(str1, rkind);
10532 if (!buf1) goto error;
10533 release1 = 1;
10534 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010535 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010536 if (n == 0)
10537 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 buf2 = _PyUnicode_AsKind(str2, rkind);
10541 if (!buf2) goto error;
10542 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010545 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 rkind = kind2;
10547 sbuf = _PyUnicode_AsKind(self, rkind);
10548 if (!sbuf) goto error;
10549 srelease = 1;
10550 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010551 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 buf1 = _PyUnicode_AsKind(str1, rkind);
10553 if (!buf1) goto error;
10554 release1 = 1;
10555 }
10556 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10557 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010558 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 PyErr_SetString(PyExc_OverflowError,
10560 "replace string is too long");
10561 goto error;
10562 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010563 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010564 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010565 _Py_INCREF_UNICODE_EMPTY();
10566 if (!unicode_empty)
10567 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010568 u = unicode_empty;
10569 goto done;
10570 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010571 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 PyErr_SetString(PyExc_OverflowError,
10573 "replace string is too long");
10574 goto error;
10575 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010576 u = PyUnicode_New(new_size, maxchar);
10577 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010579 assert(PyUnicode_KIND(u) == rkind);
10580 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 ires = i = 0;
10582 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010583 while (n-- > 0) {
10584 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010585 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010587 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010588 if (j == -1)
10589 break;
10590 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 memcpy(res + rkind * ires,
10593 sbuf + rkind * i,
10594 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010596 }
10597 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010599 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010601 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010608 memcpy(res + rkind * ires,
10609 sbuf + rkind * i,
10610 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010611 }
10612 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 /* interleave */
10614 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010615 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010617 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619 if (--n <= 0)
10620 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010621 memcpy(res + rkind * ires,
10622 sbuf + rkind * i,
10623 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 ires++;
10625 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010626 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010627 memcpy(res + rkind * ires,
10628 sbuf + rkind * i,
10629 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010630 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010631 }
10632
10633 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010634 unicode_adjust_maxchar(&u);
10635 if (u == NULL)
10636 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010638
10639 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (srelease)
10641 PyMem_FREE(sbuf);
10642 if (release1)
10643 PyMem_FREE(buf1);
10644 if (release2)
10645 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010646 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010650 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 if (srelease)
10652 PyMem_FREE(sbuf);
10653 if (release1)
10654 PyMem_FREE(buf1);
10655 if (release2)
10656 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010657 return unicode_result_unchanged(self);
10658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 error:
10660 if (srelease && sbuf)
10661 PyMem_FREE(sbuf);
10662 if (release1 && buf1)
10663 PyMem_FREE(buf1);
10664 if (release2 && buf2)
10665 PyMem_FREE(buf2);
10666 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667}
10668
10669/* --- Unicode Object Methods --------------------------------------------- */
10670
INADA Naoki3ae20562017-01-16 20:41:20 +090010671/*[clinic input]
10672str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673
INADA Naoki3ae20562017-01-16 20:41:20 +090010674Return a version of the string where each word is titlecased.
10675
10676More specifically, words start with uppercased characters and all remaining
10677cased characters have lower case.
10678[clinic start generated code]*/
10679
10680static PyObject *
10681unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010682/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010684 if (PyUnicode_READY(self) == -1)
10685 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010686 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010687}
10688
INADA Naoki3ae20562017-01-16 20:41:20 +090010689/*[clinic input]
10690str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691
INADA Naoki3ae20562017-01-16 20:41:20 +090010692Return a capitalized version of the string.
10693
10694More specifically, make the first character have upper case and the rest lower
10695case.
10696[clinic start generated code]*/
10697
10698static PyObject *
10699unicode_capitalize_impl(PyObject *self)
10700/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010702 if (PyUnicode_READY(self) == -1)
10703 return NULL;
10704 if (PyUnicode_GET_LENGTH(self) == 0)
10705 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010706 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707}
10708
INADA Naoki3ae20562017-01-16 20:41:20 +090010709/*[clinic input]
10710str.casefold as unicode_casefold
10711
10712Return a version of the string suitable for caseless comparisons.
10713[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010714
10715static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010716unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010717/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010718{
10719 if (PyUnicode_READY(self) == -1)
10720 return NULL;
10721 if (PyUnicode_IS_ASCII(self))
10722 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010723 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010724}
10725
10726
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010727/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010728
10729static int
10730convert_uc(PyObject *obj, void *addr)
10731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010733
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010734 if (!PyUnicode_Check(obj)) {
10735 PyErr_Format(PyExc_TypeError,
10736 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010737 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010738 return 0;
10739 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010740 if (PyUnicode_READY(obj) < 0)
10741 return 0;
10742 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010743 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010744 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010745 return 0;
10746 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010747 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010748 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010749}
10750
INADA Naoki3ae20562017-01-16 20:41:20 +090010751/*[clinic input]
10752str.center as unicode_center
10753
10754 width: Py_ssize_t
10755 fillchar: Py_UCS4 = ' '
10756 /
10757
10758Return a centered string of length width.
10759
10760Padding is done using the specified fill character (default is a space).
10761[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762
10763static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010764unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10765/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010767 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
Benjamin Petersonbac79492012-01-14 13:34:47 -050010769 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770 return NULL;
10771
Victor Stinnerc4b49542011-12-11 22:44:26 +010010772 if (PyUnicode_GET_LENGTH(self) >= width)
10773 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774
Victor Stinnerc4b49542011-12-11 22:44:26 +010010775 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776 left = marg / 2 + (marg & width & 1);
10777
Victor Stinner9310abb2011-10-05 00:59:23 +020010778 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779}
10780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781/* This function assumes that str1 and str2 are readied by the caller. */
10782
Marc-André Lemburge5034372000-08-08 08:04:29 +000010783static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010784unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010785{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010786#define COMPARE(TYPE1, TYPE2) \
10787 do { \
10788 TYPE1* p1 = (TYPE1 *)data1; \
10789 TYPE2* p2 = (TYPE2 *)data2; \
10790 TYPE1* end = p1 + len; \
10791 Py_UCS4 c1, c2; \
10792 for (; p1 != end; p1++, p2++) { \
10793 c1 = *p1; \
10794 c2 = *p2; \
10795 if (c1 != c2) \
10796 return (c1 < c2) ? -1 : 1; \
10797 } \
10798 } \
10799 while (0)
10800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 int kind1, kind2;
10802 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010803 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010805 kind1 = PyUnicode_KIND(str1);
10806 kind2 = PyUnicode_KIND(str2);
10807 data1 = PyUnicode_DATA(str1);
10808 data2 = PyUnicode_DATA(str2);
10809 len1 = PyUnicode_GET_LENGTH(str1);
10810 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010811 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010812
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010813 switch(kind1) {
10814 case PyUnicode_1BYTE_KIND:
10815 {
10816 switch(kind2) {
10817 case PyUnicode_1BYTE_KIND:
10818 {
10819 int cmp = memcmp(data1, data2, len);
10820 /* normalize result of memcmp() into the range [-1; 1] */
10821 if (cmp < 0)
10822 return -1;
10823 if (cmp > 0)
10824 return 1;
10825 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010826 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010827 case PyUnicode_2BYTE_KIND:
10828 COMPARE(Py_UCS1, Py_UCS2);
10829 break;
10830 case PyUnicode_4BYTE_KIND:
10831 COMPARE(Py_UCS1, Py_UCS4);
10832 break;
10833 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010834 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010835 }
10836 break;
10837 }
10838 case PyUnicode_2BYTE_KIND:
10839 {
10840 switch(kind2) {
10841 case PyUnicode_1BYTE_KIND:
10842 COMPARE(Py_UCS2, Py_UCS1);
10843 break;
10844 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010845 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010846 COMPARE(Py_UCS2, Py_UCS2);
10847 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010848 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010849 case PyUnicode_4BYTE_KIND:
10850 COMPARE(Py_UCS2, Py_UCS4);
10851 break;
10852 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010853 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010854 }
10855 break;
10856 }
10857 case PyUnicode_4BYTE_KIND:
10858 {
10859 switch(kind2) {
10860 case PyUnicode_1BYTE_KIND:
10861 COMPARE(Py_UCS4, Py_UCS1);
10862 break;
10863 case PyUnicode_2BYTE_KIND:
10864 COMPARE(Py_UCS4, Py_UCS2);
10865 break;
10866 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010867 {
10868#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10869 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10870 /* normalize result of wmemcmp() into the range [-1; 1] */
10871 if (cmp < 0)
10872 return -1;
10873 if (cmp > 0)
10874 return 1;
10875#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010876 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010877#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010878 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010879 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010880 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010881 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010882 }
10883 break;
10884 }
10885 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010886 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010887 }
10888
Victor Stinner770e19e2012-10-04 22:59:45 +020010889 if (len1 == len2)
10890 return 0;
10891 if (len1 < len2)
10892 return -1;
10893 else
10894 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010895
10896#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010897}
10898
Benjamin Peterson621b4302016-09-09 13:54:34 -070010899static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010900unicode_compare_eq(PyObject *str1, PyObject *str2)
10901{
10902 int kind;
10903 void *data1, *data2;
10904 Py_ssize_t len;
10905 int cmp;
10906
Victor Stinnere5567ad2012-10-23 02:48:49 +020010907 len = PyUnicode_GET_LENGTH(str1);
10908 if (PyUnicode_GET_LENGTH(str2) != len)
10909 return 0;
10910 kind = PyUnicode_KIND(str1);
10911 if (PyUnicode_KIND(str2) != kind)
10912 return 0;
10913 data1 = PyUnicode_DATA(str1);
10914 data2 = PyUnicode_DATA(str2);
10915
10916 cmp = memcmp(data1, data2, len * kind);
10917 return (cmp == 0);
10918}
10919
10920
Alexander Belopolsky40018472011-02-26 01:02:56 +000010921int
10922PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10925 if (PyUnicode_READY(left) == -1 ||
10926 PyUnicode_READY(right) == -1)
10927 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010928
10929 /* a string is equal to itself */
10930 if (left == right)
10931 return 0;
10932
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010933 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010934 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010935 PyErr_Format(PyExc_TypeError,
10936 "Can't compare %.100s and %.100s",
10937 left->ob_type->tp_name,
10938 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939 return -1;
10940}
10941
Martin v. Löwis5b222132007-06-10 09:51:05 +000010942int
10943PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10944{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 Py_ssize_t i;
10946 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010948 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949
Victor Stinner910337b2011-10-03 03:20:16 +020010950 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010951 if (!PyUnicode_IS_READY(uni)) {
10952 const wchar_t *ws = _PyUnicode_WSTR(uni);
10953 /* Compare Unicode string and source character set string */
10954 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10955 if (chr != ustr[i])
10956 return (chr < ustr[i]) ? -1 : 1;
10957 }
10958 /* This check keeps Python strings that end in '\0' from comparing equal
10959 to C strings identical up to that point. */
10960 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10961 return 1; /* uni is longer */
10962 if (ustr[i])
10963 return -1; /* str is longer */
10964 return 0;
10965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010966 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010967 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010968 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010969 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010970 size_t len, len2 = strlen(str);
10971 int cmp;
10972
10973 len = Py_MIN(len1, len2);
10974 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010975 if (cmp != 0) {
10976 if (cmp < 0)
10977 return -1;
10978 else
10979 return 1;
10980 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010981 if (len1 > len2)
10982 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010983 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010984 return -1; /* str is longer */
10985 return 0;
10986 }
10987 else {
10988 void *data = PyUnicode_DATA(uni);
10989 /* Compare Unicode string and source character set string */
10990 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010991 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010992 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10993 /* This check keeps Python strings that end in '\0' from comparing equal
10994 to C strings identical up to that point. */
10995 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10996 return 1; /* uni is longer */
10997 if (str[i])
10998 return -1; /* str is longer */
10999 return 0;
11000 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011001}
11002
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011003static int
11004non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11005{
11006 size_t i, len;
11007 const wchar_t *p;
11008 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11009 if (strlen(str) != len)
11010 return 0;
11011 p = _PyUnicode_WSTR(unicode);
11012 assert(p);
11013 for (i = 0; i < len; i++) {
11014 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011015 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011016 return 0;
11017 }
11018 return 1;
11019}
11020
11021int
11022_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11023{
11024 size_t len;
11025 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011026 assert(str);
11027#ifndef NDEBUG
11028 for (const char *p = str; *p; p++) {
11029 assert((unsigned char)*p < 128);
11030 }
11031#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011032 if (PyUnicode_READY(unicode) == -1) {
11033 /* Memory error or bad data */
11034 PyErr_Clear();
11035 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11036 }
11037 if (!PyUnicode_IS_ASCII(unicode))
11038 return 0;
11039 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11040 return strlen(str) == len &&
11041 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11042}
11043
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011044int
11045_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11046{
11047 PyObject *right_uni;
11048 Py_hash_t hash;
11049
11050 assert(_PyUnicode_CHECK(left));
11051 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011052#ifndef NDEBUG
11053 for (const char *p = right->string; *p; p++) {
11054 assert((unsigned char)*p < 128);
11055 }
11056#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011057
11058 if (PyUnicode_READY(left) == -1) {
11059 /* memory error or bad data */
11060 PyErr_Clear();
11061 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11062 }
11063
11064 if (!PyUnicode_IS_ASCII(left))
11065 return 0;
11066
11067 right_uni = _PyUnicode_FromId(right); /* borrowed */
11068 if (right_uni == NULL) {
11069 /* memory error or bad data */
11070 PyErr_Clear();
11071 return _PyUnicode_EqualToASCIIString(left, right->string);
11072 }
11073
11074 if (left == right_uni)
11075 return 1;
11076
11077 if (PyUnicode_CHECK_INTERNED(left))
11078 return 0;
11079
INADA Naoki7cc95f52018-01-28 02:07:09 +090011080 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011081 hash = _PyUnicode_HASH(left);
11082 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11083 return 0;
11084
11085 return unicode_compare_eq(left, right_uni);
11086}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011087
Alexander Belopolsky40018472011-02-26 01:02:56 +000011088PyObject *
11089PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011090{
11091 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011092
Victor Stinnere5567ad2012-10-23 02:48:49 +020011093 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11094 Py_RETURN_NOTIMPLEMENTED;
11095
11096 if (PyUnicode_READY(left) == -1 ||
11097 PyUnicode_READY(right) == -1)
11098 return NULL;
11099
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011100 if (left == right) {
11101 switch (op) {
11102 case Py_EQ:
11103 case Py_LE:
11104 case Py_GE:
11105 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011106 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011107 case Py_NE:
11108 case Py_LT:
11109 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011110 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011111 default:
11112 PyErr_BadArgument();
11113 return NULL;
11114 }
11115 }
11116 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011117 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011118 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011119 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011120 }
11121 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011122 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011123 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011124 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011125}
11126
Alexander Belopolsky40018472011-02-26 01:02:56 +000011127int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011128_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11129{
11130 return unicode_eq(aa, bb);
11131}
11132
11133int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011134PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011135{
Victor Stinner77282cb2013-04-14 19:22:47 +020011136 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137 void *buf1, *buf2;
11138 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011139 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011140
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011141 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011142 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011143 "'in <string>' requires string as left operand, not %.100s",
11144 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011145 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011146 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011147 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011148 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011149 if (ensure_unicode(str) < 0)
11150 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011153 kind2 = PyUnicode_KIND(substr);
11154 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011155 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011157 len2 = PyUnicode_GET_LENGTH(substr);
11158 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011159 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011160 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011161 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011162 if (len2 == 1) {
11163 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11164 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011165 return result;
11166 }
11167 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011168 buf2 = _PyUnicode_AsKind(substr, kind1);
11169 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011170 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172
Victor Stinner77282cb2013-04-14 19:22:47 +020011173 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 case PyUnicode_1BYTE_KIND:
11175 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11176 break;
11177 case PyUnicode_2BYTE_KIND:
11178 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11179 break;
11180 case PyUnicode_4BYTE_KIND:
11181 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11182 break;
11183 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011184 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011186
Victor Stinner77282cb2013-04-14 19:22:47 +020011187 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 PyMem_Free(buf2);
11189
Guido van Rossum403d68b2000-03-13 15:55:09 +000011190 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011191}
11192
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193/* Concat to string or Unicode object giving a new Unicode object. */
11194
Alexander Belopolsky40018472011-02-26 01:02:56 +000011195PyObject *
11196PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011199 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011200 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011202 if (ensure_unicode(left) < 0)
11203 return NULL;
11204
11205 if (!PyUnicode_Check(right)) {
11206 PyErr_Format(PyExc_TypeError,
11207 "can only concatenate str (not \"%.200s\") to str",
11208 right->ob_type->tp_name);
11209 return NULL;
11210 }
11211 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011212 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213
11214 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011215 if (left == unicode_empty)
11216 return PyUnicode_FromObject(right);
11217 if (right == unicode_empty)
11218 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011220 left_len = PyUnicode_GET_LENGTH(left);
11221 right_len = PyUnicode_GET_LENGTH(right);
11222 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011223 PyErr_SetString(PyExc_OverflowError,
11224 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011225 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011226 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011227 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011228
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011229 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11230 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011231 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011234 result = PyUnicode_New(new_len, maxchar);
11235 if (result == NULL)
11236 return NULL;
11237 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11238 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11239 assert(_PyUnicode_CheckConsistency(result, 1));
11240 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241}
11242
Walter Dörwald1ab83302007-05-18 17:15:44 +000011243void
Victor Stinner23e56682011-10-03 03:54:37 +020011244PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011245{
Victor Stinner23e56682011-10-03 03:54:37 +020011246 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011247 Py_UCS4 maxchar, maxchar2;
11248 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011249
11250 if (p_left == NULL) {
11251 if (!PyErr_Occurred())
11252 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011253 return;
11254 }
Victor Stinner23e56682011-10-03 03:54:37 +020011255 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011256 if (right == NULL || left == NULL
11257 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011258 if (!PyErr_Occurred())
11259 PyErr_BadInternalCall();
11260 goto error;
11261 }
11262
Benjamin Petersonbac79492012-01-14 13:34:47 -050011263 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011264 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011265 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011266 goto error;
11267
Victor Stinner488fa492011-12-12 00:01:39 +010011268 /* Shortcuts */
11269 if (left == unicode_empty) {
11270 Py_DECREF(left);
11271 Py_INCREF(right);
11272 *p_left = right;
11273 return;
11274 }
11275 if (right == unicode_empty)
11276 return;
11277
11278 left_len = PyUnicode_GET_LENGTH(left);
11279 right_len = PyUnicode_GET_LENGTH(right);
11280 if (left_len > PY_SSIZE_T_MAX - right_len) {
11281 PyErr_SetString(PyExc_OverflowError,
11282 "strings are too large to concat");
11283 goto error;
11284 }
11285 new_len = left_len + right_len;
11286
11287 if (unicode_modifiable(left)
11288 && PyUnicode_CheckExact(right)
11289 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011290 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11291 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011292 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011293 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011294 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11295 {
11296 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011297 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011298 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011299
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011300 /* copy 'right' into the newly allocated area of 'left' */
11301 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011302 }
Victor Stinner488fa492011-12-12 00:01:39 +010011303 else {
11304 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11305 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011306 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011307
Victor Stinner488fa492011-12-12 00:01:39 +010011308 /* Concat the two Unicode strings */
11309 res = PyUnicode_New(new_len, maxchar);
11310 if (res == NULL)
11311 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011312 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11313 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011314 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011315 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011316 }
11317 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011318 return;
11319
11320error:
Victor Stinner488fa492011-12-12 00:01:39 +010011321 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011322}
11323
11324void
11325PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11326{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011327 PyUnicode_Append(pleft, right);
11328 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011329}
11330
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011331/*
11332Wraps stringlib_parse_args_finds() and additionally ensures that the
11333first argument is a unicode object.
11334*/
11335
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011336static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011337parse_args_finds_unicode(const char * function_name, PyObject *args,
11338 PyObject **substring,
11339 Py_ssize_t *start, Py_ssize_t *end)
11340{
11341 if(stringlib_parse_args_finds(function_name, args, substring,
11342 start, end)) {
11343 if (ensure_unicode(*substring) < 0)
11344 return 0;
11345 return 1;
11346 }
11347 return 0;
11348}
11349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011350PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011351 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011353Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011354string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011355interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356
11357static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011358unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011360 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011361 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011362 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011364 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 void *buf1, *buf2;
11366 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011368 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011369 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 kind1 = PyUnicode_KIND(self);
11372 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011373 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011374 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 len1 = PyUnicode_GET_LENGTH(self);
11377 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011379 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011380 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011381
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011382 buf1 = PyUnicode_DATA(self);
11383 buf2 = PyUnicode_DATA(substring);
11384 if (kind2 != kind1) {
11385 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011386 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011387 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011388 }
11389 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 case PyUnicode_1BYTE_KIND:
11391 iresult = ucs1lib_count(
11392 ((Py_UCS1*)buf1) + start, end - start,
11393 buf2, len2, PY_SSIZE_T_MAX
11394 );
11395 break;
11396 case PyUnicode_2BYTE_KIND:
11397 iresult = ucs2lib_count(
11398 ((Py_UCS2*)buf1) + start, end - start,
11399 buf2, len2, PY_SSIZE_T_MAX
11400 );
11401 break;
11402 case PyUnicode_4BYTE_KIND:
11403 iresult = ucs4lib_count(
11404 ((Py_UCS4*)buf1) + start, end - start,
11405 buf2, len2, PY_SSIZE_T_MAX
11406 );
11407 break;
11408 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011409 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 }
11411
11412 result = PyLong_FromSsize_t(iresult);
11413
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011414 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417 return result;
11418}
11419
INADA Naoki3ae20562017-01-16 20:41:20 +090011420/*[clinic input]
11421str.encode as unicode_encode
11422
11423 encoding: str(c_default="NULL") = 'utf-8'
11424 The encoding in which to encode the string.
11425 errors: str(c_default="NULL") = 'strict'
11426 The error handling scheme to use for encoding errors.
11427 The default is 'strict' meaning that encoding errors raise a
11428 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11429 'xmlcharrefreplace' as well as any other name registered with
11430 codecs.register_error that can handle UnicodeEncodeErrors.
11431
11432Encode the string using the codec registered for encoding.
11433[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
11435static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011436unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011437/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011439 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011440}
11441
INADA Naoki3ae20562017-01-16 20:41:20 +090011442/*[clinic input]
11443str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
INADA Naoki3ae20562017-01-16 20:41:20 +090011445 tabsize: int = 8
11446
11447Return a copy where all tab characters are expanded using spaces.
11448
11449If tabsize is not given, a tab size of 8 characters is assumed.
11450[clinic start generated code]*/
11451
11452static PyObject *
11453unicode_expandtabs_impl(PyObject *self, int tabsize)
11454/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011456 Py_ssize_t i, j, line_pos, src_len, incr;
11457 Py_UCS4 ch;
11458 PyObject *u;
11459 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011460 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011461 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Antoine Pitrou22425222011-10-04 19:10:51 +020011463 if (PyUnicode_READY(self) == -1)
11464 return NULL;
11465
Thomas Wouters7e474022000-07-16 12:04:32 +000011466 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011467 src_len = PyUnicode_GET_LENGTH(self);
11468 i = j = line_pos = 0;
11469 kind = PyUnicode_KIND(self);
11470 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011471 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011472 for (; i < src_len; i++) {
11473 ch = PyUnicode_READ(kind, src_data, i);
11474 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011475 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011477 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 goto overflow;
11480 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011482 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 goto overflow;
11487 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +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 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011493 if (!found)
11494 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011495
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 if (!u)
11499 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011500 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501
Antoine Pitroue71d5742011-10-04 15:55:09 +020011502 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
Antoine Pitroue71d5742011-10-04 15:55:09 +020011504 for (; i < src_len; i++) {
11505 ch = PyUnicode_READ(kind, src_data, i);
11506 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011508 incr = tabsize - (line_pos % tabsize);
11509 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011510 FILL(kind, dest_data, ' ', j, incr);
11511 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011513 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 line_pos++;
11516 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011517 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011518 if (ch == '\n' || ch == '\r')
11519 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011521 }
11522 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011523 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011524
Antoine Pitroue71d5742011-10-04 15:55:09 +020011525 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011526 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528}
11529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011530PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532\n\
11533Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011534such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535arguments start and end are interpreted as in slice notation.\n\
11536\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011537Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538
11539static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011542 /* initialize variables to prevent gcc warning */
11543 PyObject *substring = NULL;
11544 Py_ssize_t start = 0;
11545 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011546 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011548 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011551 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011554 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 if (result == -2)
11557 return NULL;
11558
Christian Heimes217cfd12007-12-02 14:31:20 +000011559 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560}
11561
11562static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011563unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011565 void *data;
11566 enum PyUnicode_Kind kind;
11567 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011568
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011569 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011570 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011572 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011573 if (PyUnicode_READY(self) == -1) {
11574 return NULL;
11575 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011576 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11577 PyErr_SetString(PyExc_IndexError, "string index out of range");
11578 return NULL;
11579 }
11580 kind = PyUnicode_KIND(self);
11581 data = PyUnicode_DATA(self);
11582 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011583 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Guido van Rossumc2504932007-09-18 19:42:40 +000011586/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011587 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011588static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Guido van Rossumc2504932007-09-18 19:42:40 +000011591 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011592 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011593
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011594#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011595 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011596#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 if (_PyUnicode_HASH(self) != -1)
11598 return _PyUnicode_HASH(self);
11599 if (PyUnicode_READY(self) == -1)
11600 return -1;
11601 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011602 /*
11603 We make the hash of the empty string be 0, rather than using
11604 (prefix ^ suffix), since this slightly obfuscates the hash secret
11605 */
11606 if (len == 0) {
11607 _PyUnicode_HASH(self) = 0;
11608 return 0;
11609 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011610 x = _Py_HashBytes(PyUnicode_DATA(self),
11611 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011613 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614}
11615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011616PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618\n\
oldkaa0735f2018-02-02 16:52:55 +080011619Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011620such that sub is contained within S[start:end]. Optional\n\
11621arguments start and end are interpreted as in slice notation.\n\
11622\n\
11623Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
11625static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011628 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011629 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011630 PyObject *substring = NULL;
11631 Py_ssize_t start = 0;
11632 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011634 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011637 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011640 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 if (result == -2)
11643 return NULL;
11644
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645 if (result < 0) {
11646 PyErr_SetString(PyExc_ValueError, "substring not found");
11647 return NULL;
11648 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011649
Christian Heimes217cfd12007-12-02 14:31:20 +000011650 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651}
11652
INADA Naoki3ae20562017-01-16 20:41:20 +090011653/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011654str.isascii as unicode_isascii
11655
11656Return True if all characters in the string are ASCII, False otherwise.
11657
11658ASCII characters have code points in the range U+0000-U+007F.
11659Empty string is ASCII too.
11660[clinic start generated code]*/
11661
11662static PyObject *
11663unicode_isascii_impl(PyObject *self)
11664/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11665{
11666 if (PyUnicode_READY(self) == -1) {
11667 return NULL;
11668 }
11669 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11670}
11671
11672/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011673str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674
INADA Naoki3ae20562017-01-16 20:41:20 +090011675Return True if the string is a lowercase string, False otherwise.
11676
11677A string is lowercase if all cased characters in the string are lowercase and
11678there is at least one cased character in the string.
11679[clinic start generated code]*/
11680
11681static PyObject *
11682unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011683/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 Py_ssize_t i, length;
11686 int kind;
11687 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688 int cased;
11689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (PyUnicode_READY(self) == -1)
11691 return NULL;
11692 length = PyUnicode_GET_LENGTH(self);
11693 kind = PyUnicode_KIND(self);
11694 data = PyUnicode_DATA(self);
11695
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 if (length == 1)
11698 return PyBool_FromLong(
11699 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011701 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011702 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011703 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011704
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 for (i = 0; i < length; i++) {
11707 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011708
Benjamin Peterson29060642009-01-31 22:14:21 +000011709 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011710 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011711 else if (!cased && Py_UNICODE_ISLOWER(ch))
11712 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011714 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715}
11716
INADA Naoki3ae20562017-01-16 20:41:20 +090011717/*[clinic input]
11718str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
INADA Naoki3ae20562017-01-16 20:41:20 +090011720Return True if the string is an uppercase string, False otherwise.
11721
11722A string is uppercase if all cased characters in the string are uppercase and
11723there is at least one cased character in the string.
11724[clinic start generated code]*/
11725
11726static PyObject *
11727unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011728/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 Py_ssize_t i, length;
11731 int kind;
11732 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733 int cased;
11734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 if (PyUnicode_READY(self) == -1)
11736 return NULL;
11737 length = PyUnicode_GET_LENGTH(self);
11738 kind = PyUnicode_KIND(self);
11739 data = PyUnicode_DATA(self);
11740
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 if (length == 1)
11743 return PyBool_FromLong(
11744 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011746 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011748 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011749
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 for (i = 0; i < length; i++) {
11752 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011753
Benjamin Peterson29060642009-01-31 22:14:21 +000011754 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011755 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 else if (!cased && Py_UNICODE_ISUPPER(ch))
11757 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011759 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760}
11761
INADA Naoki3ae20562017-01-16 20:41:20 +090011762/*[clinic input]
11763str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
INADA Naoki3ae20562017-01-16 20:41:20 +090011765Return True if the string is a title-cased string, False otherwise.
11766
11767In a title-cased string, upper- and title-case characters may only
11768follow uncased characters and lowercase characters only cased ones.
11769[clinic start generated code]*/
11770
11771static PyObject *
11772unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011773/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 Py_ssize_t i, length;
11776 int kind;
11777 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778 int cased, previous_is_cased;
11779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 if (PyUnicode_READY(self) == -1)
11781 return NULL;
11782 length = PyUnicode_GET_LENGTH(self);
11783 kind = PyUnicode_KIND(self);
11784 data = PyUnicode_DATA(self);
11785
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787 if (length == 1) {
11788 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11789 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11790 (Py_UNICODE_ISUPPER(ch) != 0));
11791 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011793 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011795 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011796
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797 cased = 0;
11798 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 for (i = 0; i < length; i++) {
11800 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011801
Benjamin Peterson29060642009-01-31 22:14:21 +000011802 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11803 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011804 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011805 previous_is_cased = 1;
11806 cased = 1;
11807 }
11808 else if (Py_UNICODE_ISLOWER(ch)) {
11809 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011810 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011811 previous_is_cased = 1;
11812 cased = 1;
11813 }
11814 else
11815 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011817 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011818}
11819
INADA Naoki3ae20562017-01-16 20:41:20 +090011820/*[clinic input]
11821str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822
INADA Naoki3ae20562017-01-16 20:41:20 +090011823Return True if the string is a whitespace string, False otherwise.
11824
11825A string is whitespace if all characters in the string are whitespace and there
11826is at least one character in the string.
11827[clinic start generated code]*/
11828
11829static PyObject *
11830unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011831/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011832{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011833 Py_ssize_t i, length;
11834 int kind;
11835 void *data;
11836
11837 if (PyUnicode_READY(self) == -1)
11838 return NULL;
11839 length = PyUnicode_GET_LENGTH(self);
11840 kind = PyUnicode_KIND(self);
11841 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011844 if (length == 1)
11845 return PyBool_FromLong(
11846 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011848 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011849 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011850 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011851
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 for (i = 0; i < length; i++) {
11853 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011854 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011855 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011857 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858}
11859
INADA Naoki3ae20562017-01-16 20:41:20 +090011860/*[clinic input]
11861str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011862
INADA Naoki3ae20562017-01-16 20:41:20 +090011863Return True if the string is an alphabetic string, False otherwise.
11864
11865A string is alphabetic if all characters in the string are alphabetic and there
11866is at least one character in the string.
11867[clinic start generated code]*/
11868
11869static PyObject *
11870unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011871/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 Py_ssize_t i, length;
11874 int kind;
11875 void *data;
11876
11877 if (PyUnicode_READY(self) == -1)
11878 return NULL;
11879 length = PyUnicode_GET_LENGTH(self);
11880 kind = PyUnicode_KIND(self);
11881 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011882
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011883 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 if (length == 1)
11885 return PyBool_FromLong(
11886 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011887
11888 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011890 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011892 for (i = 0; i < length; i++) {
11893 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011894 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011895 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011896 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011897}
11898
INADA Naoki3ae20562017-01-16 20:41:20 +090011899/*[clinic input]
11900str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011901
INADA Naoki3ae20562017-01-16 20:41:20 +090011902Return True if the string is an alpha-numeric string, False otherwise.
11903
11904A string is alpha-numeric if all characters in the string are alpha-numeric and
11905there is at least one character in the string.
11906[clinic start generated code]*/
11907
11908static PyObject *
11909unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011910/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011911{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 int kind;
11913 void *data;
11914 Py_ssize_t len, i;
11915
11916 if (PyUnicode_READY(self) == -1)
11917 return NULL;
11918
11919 kind = PyUnicode_KIND(self);
11920 data = PyUnicode_DATA(self);
11921 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011922
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011923 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 if (len == 1) {
11925 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11926 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11927 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011928
11929 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011931 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 for (i = 0; i < len; i++) {
11934 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011935 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011936 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011937 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011938 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011939}
11940
INADA Naoki3ae20562017-01-16 20:41:20 +090011941/*[clinic input]
11942str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943
INADA Naoki3ae20562017-01-16 20:41:20 +090011944Return True if the string is a decimal string, False otherwise.
11945
11946A string is a decimal string if all characters in the string are decimal and
11947there is at least one character in the string.
11948[clinic start generated code]*/
11949
11950static PyObject *
11951unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011952/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 Py_ssize_t i, length;
11955 int kind;
11956 void *data;
11957
11958 if (PyUnicode_READY(self) == -1)
11959 return NULL;
11960 length = PyUnicode_GET_LENGTH(self);
11961 kind = PyUnicode_KIND(self);
11962 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011965 if (length == 1)
11966 return PyBool_FromLong(
11967 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011969 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011971 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 for (i = 0; i < length; i++) {
11974 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011975 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011977 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978}
11979
INADA Naoki3ae20562017-01-16 20:41:20 +090011980/*[clinic input]
11981str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011982
INADA Naoki3ae20562017-01-16 20:41:20 +090011983Return True if the string is a digit string, False otherwise.
11984
11985A string is a digit string if all characters in the string are digits and there
11986is at least one character in the string.
11987[clinic start generated code]*/
11988
11989static PyObject *
11990unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011991/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011993 Py_ssize_t i, length;
11994 int kind;
11995 void *data;
11996
11997 if (PyUnicode_READY(self) == -1)
11998 return NULL;
11999 length = PyUnicode_GET_LENGTH(self);
12000 kind = PyUnicode_KIND(self);
12001 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 if (length == 1) {
12005 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12006 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12007 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012008
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012009 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012011 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 for (i = 0; i < length; i++) {
12014 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012015 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012017 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018}
12019
INADA Naoki3ae20562017-01-16 20:41:20 +090012020/*[clinic input]
12021str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022
INADA Naoki3ae20562017-01-16 20:41:20 +090012023Return True if the string is a numeric string, False otherwise.
12024
12025A string is numeric if all characters in the string are numeric and there is at
12026least one character in the string.
12027[clinic start generated code]*/
12028
12029static PyObject *
12030unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012031/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 Py_ssize_t i, length;
12034 int kind;
12035 void *data;
12036
12037 if (PyUnicode_READY(self) == -1)
12038 return NULL;
12039 length = PyUnicode_GET_LENGTH(self);
12040 kind = PyUnicode_KIND(self);
12041 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 if (length == 1)
12045 return PyBool_FromLong(
12046 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012048 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012050 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012052 for (i = 0; i < length; i++) {
12053 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012054 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012056 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057}
12058
Martin v. Löwis47383402007-08-15 07:32:56 +000012059int
12060PyUnicode_IsIdentifier(PyObject *self)
12061{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 int kind;
12063 void *data;
12064 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012065 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 if (PyUnicode_READY(self) == -1) {
12068 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012069 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 }
12071
12072 /* Special case for empty strings */
12073 if (PyUnicode_GET_LENGTH(self) == 0)
12074 return 0;
12075 kind = PyUnicode_KIND(self);
12076 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012077
12078 /* PEP 3131 says that the first character must be in
12079 XID_Start and subsequent characters in XID_Continue,
12080 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012081 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012082 letters, digits, underscore). However, given the current
12083 definition of XID_Start and XID_Continue, it is sufficient
12084 to check just for these, except that _ must be allowed
12085 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012087 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012088 return 0;
12089
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012090 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012092 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012093 return 1;
12094}
12095
INADA Naoki3ae20562017-01-16 20:41:20 +090012096/*[clinic input]
12097str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012098
INADA Naoki3ae20562017-01-16 20:41:20 +090012099Return True if the string is a valid Python identifier, False otherwise.
12100
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012101Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012102such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012103[clinic start generated code]*/
12104
12105static PyObject *
12106unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012107/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012108{
12109 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12110}
12111
INADA Naoki3ae20562017-01-16 20:41:20 +090012112/*[clinic input]
12113str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012114
INADA Naoki3ae20562017-01-16 20:41:20 +090012115Return True if the string is printable, False otherwise.
12116
12117A string is printable if all of its characters are considered printable in
12118repr() or if it is empty.
12119[clinic start generated code]*/
12120
12121static PyObject *
12122unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012123/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012124{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 Py_ssize_t i, length;
12126 int kind;
12127 void *data;
12128
12129 if (PyUnicode_READY(self) == -1)
12130 return NULL;
12131 length = PyUnicode_GET_LENGTH(self);
12132 kind = PyUnicode_KIND(self);
12133 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012134
12135 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136 if (length == 1)
12137 return PyBool_FromLong(
12138 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012140 for (i = 0; i < length; i++) {
12141 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012142 Py_RETURN_FALSE;
12143 }
12144 }
12145 Py_RETURN_TRUE;
12146}
12147
INADA Naoki3ae20562017-01-16 20:41:20 +090012148/*[clinic input]
12149str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150
INADA Naoki3ae20562017-01-16 20:41:20 +090012151 iterable: object
12152 /
12153
12154Concatenate any number of strings.
12155
Martin Panter91a88662017-01-24 00:30:06 +000012156The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012157The result is returned as a new string.
12158
12159Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12160[clinic start generated code]*/
12161
12162static PyObject *
12163unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012164/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165{
INADA Naoki3ae20562017-01-16 20:41:20 +090012166 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167}
12168
Martin v. Löwis18e16552006-02-15 17:27:45 +000012169static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012170unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 if (PyUnicode_READY(self) == -1)
12173 return -1;
12174 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175}
12176
INADA Naoki3ae20562017-01-16 20:41:20 +090012177/*[clinic input]
12178str.ljust as unicode_ljust
12179
12180 width: Py_ssize_t
12181 fillchar: Py_UCS4 = ' '
12182 /
12183
12184Return a left-justified string of length width.
12185
12186Padding is done using the specified fill character (default is a space).
12187[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188
12189static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012190unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12191/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012193 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012194 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
Victor Stinnerc4b49542011-12-11 22:44:26 +010012196 if (PyUnicode_GET_LENGTH(self) >= width)
12197 return unicode_result_unchanged(self);
12198
12199 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200}
12201
INADA Naoki3ae20562017-01-16 20:41:20 +090012202/*[clinic input]
12203str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204
INADA Naoki3ae20562017-01-16 20:41:20 +090012205Return a copy of the string converted to lowercase.
12206[clinic start generated code]*/
12207
12208static PyObject *
12209unicode_lower_impl(PyObject *self)
12210/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012212 if (PyUnicode_READY(self) == -1)
12213 return NULL;
12214 if (PyUnicode_IS_ASCII(self))
12215 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012216 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217}
12218
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012219#define LEFTSTRIP 0
12220#define RIGHTSTRIP 1
12221#define BOTHSTRIP 2
12222
12223/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012224static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012225
INADA Naoki3ae20562017-01-16 20:41:20 +090012226#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012227
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012228/* externally visible for str.strip(unicode) */
12229PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012230_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012231{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232 void *data;
12233 int kind;
12234 Py_ssize_t i, j, len;
12235 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012236 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012237
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12239 return NULL;
12240
12241 kind = PyUnicode_KIND(self);
12242 data = PyUnicode_DATA(self);
12243 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012244 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012245 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12246 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012247 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012248
Benjamin Peterson14339b62009-01-31 16:36:08 +000012249 i = 0;
12250 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012251 while (i < len) {
12252 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12253 if (!BLOOM(sepmask, ch))
12254 break;
12255 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12256 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012257 i++;
12258 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012259 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012260
Benjamin Peterson14339b62009-01-31 16:36:08 +000012261 j = len;
12262 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012263 j--;
12264 while (j >= i) {
12265 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12266 if (!BLOOM(sepmask, ch))
12267 break;
12268 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12269 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012270 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012271 }
12272
Benjamin Peterson29060642009-01-31 22:14:21 +000012273 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012274 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012275
Victor Stinner7931d9a2011-11-04 00:22:48 +010012276 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277}
12278
12279PyObject*
12280PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12281{
12282 unsigned char *data;
12283 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012284 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285
Victor Stinnerde636f32011-10-01 03:55:54 +020012286 if (PyUnicode_READY(self) == -1)
12287 return NULL;
12288
Victor Stinner684d5fd2012-05-03 02:32:34 +020012289 length = PyUnicode_GET_LENGTH(self);
12290 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012291
Victor Stinner684d5fd2012-05-03 02:32:34 +020012292 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012293 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294
Victor Stinnerde636f32011-10-01 03:55:54 +020012295 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012296 PyErr_SetString(PyExc_IndexError, "string index out of range");
12297 return NULL;
12298 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012299 if (start >= length || end < start)
12300 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012301
Victor Stinner684d5fd2012-05-03 02:32:34 +020012302 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012303 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012304 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012305 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012306 }
12307 else {
12308 kind = PyUnicode_KIND(self);
12309 data = PyUnicode_1BYTE_DATA(self);
12310 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012311 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012312 length);
12313 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315
12316static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012317do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 Py_ssize_t len, i, j;
12320
12321 if (PyUnicode_READY(self) == -1)
12322 return NULL;
12323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012325
Victor Stinnercc7af722013-04-09 22:39:24 +020012326 if (PyUnicode_IS_ASCII(self)) {
12327 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12328
12329 i = 0;
12330 if (striptype != RIGHTSTRIP) {
12331 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012332 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012333 if (!_Py_ascii_whitespace[ch])
12334 break;
12335 i++;
12336 }
12337 }
12338
12339 j = len;
12340 if (striptype != LEFTSTRIP) {
12341 j--;
12342 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012343 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012344 if (!_Py_ascii_whitespace[ch])
12345 break;
12346 j--;
12347 }
12348 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012349 }
12350 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012351 else {
12352 int kind = PyUnicode_KIND(self);
12353 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354
Victor Stinnercc7af722013-04-09 22:39:24 +020012355 i = 0;
12356 if (striptype != RIGHTSTRIP) {
12357 while (i < len) {
12358 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12359 if (!Py_UNICODE_ISSPACE(ch))
12360 break;
12361 i++;
12362 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012363 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012364
12365 j = len;
12366 if (striptype != LEFTSTRIP) {
12367 j--;
12368 while (j >= i) {
12369 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12370 if (!Py_UNICODE_ISSPACE(ch))
12371 break;
12372 j--;
12373 }
12374 j++;
12375 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012376 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012377
Victor Stinner7931d9a2011-11-04 00:22:48 +010012378 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012379}
12380
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012381
12382static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012383do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012384{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012385 if (sep != NULL && sep != Py_None) {
12386 if (PyUnicode_Check(sep))
12387 return _PyUnicode_XStrip(self, striptype, sep);
12388 else {
12389 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012390 "%s arg must be None or str",
12391 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012392 return NULL;
12393 }
12394 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012395
Benjamin Peterson14339b62009-01-31 16:36:08 +000012396 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012397}
12398
12399
INADA Naoki3ae20562017-01-16 20:41:20 +090012400/*[clinic input]
12401str.strip as unicode_strip
12402
12403 chars: object = None
12404 /
12405
Victor Stinner0c4a8282017-01-17 02:21:47 +010012406Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012407
12408If chars is given and not None, remove characters in chars instead.
12409[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012410
12411static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012412unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012413/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012414{
INADA Naoki3ae20562017-01-16 20:41:20 +090012415 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012416}
12417
12418
INADA Naoki3ae20562017-01-16 20:41:20 +090012419/*[clinic input]
12420str.lstrip as unicode_lstrip
12421
12422 chars: object = NULL
12423 /
12424
12425Return a copy of the string with leading whitespace removed.
12426
12427If chars is given and not None, remove characters in chars instead.
12428[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012429
12430static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012431unicode_lstrip_impl(PyObject *self, PyObject *chars)
12432/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012433{
INADA Naoki3ae20562017-01-16 20:41:20 +090012434 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012435}
12436
12437
INADA Naoki3ae20562017-01-16 20:41:20 +090012438/*[clinic input]
12439str.rstrip as unicode_rstrip
12440
12441 chars: object = NULL
12442 /
12443
12444Return a copy of the string with trailing whitespace removed.
12445
12446If chars is given and not None, remove characters in chars instead.
12447[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012448
12449static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012450unicode_rstrip_impl(PyObject *self, PyObject *chars)
12451/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012452{
INADA Naoki3ae20562017-01-16 20:41:20 +090012453 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012454}
12455
12456
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012458unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012460 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012461 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012462
Serhiy Storchaka05997252013-01-26 12:14:02 +020012463 if (len < 1)
12464 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465
Victor Stinnerc4b49542011-12-11 22:44:26 +010012466 /* no repeat, return original string */
12467 if (len == 1)
12468 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012469
Benjamin Petersonbac79492012-01-14 13:34:47 -050012470 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 return NULL;
12472
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012473 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012474 PyErr_SetString(PyExc_OverflowError,
12475 "repeated string is too long");
12476 return NULL;
12477 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012479
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012480 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481 if (!u)
12482 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012483 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485 if (PyUnicode_GET_LENGTH(str) == 1) {
12486 const int kind = PyUnicode_KIND(str);
12487 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012488 if (kind == PyUnicode_1BYTE_KIND) {
12489 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012490 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012491 }
12492 else if (kind == PyUnicode_2BYTE_KIND) {
12493 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012494 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012495 ucs2[n] = fill_char;
12496 } else {
12497 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12498 assert(kind == PyUnicode_4BYTE_KIND);
12499 for (n = 0; n < len; ++n)
12500 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012501 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 }
12503 else {
12504 /* number of characters copied this far */
12505 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012506 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012507 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012508 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012509 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012510 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012512 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012513 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012514 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515 }
12516
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012517 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012518 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519}
12520
Alexander Belopolsky40018472011-02-26 01:02:56 +000012521PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012522PyUnicode_Replace(PyObject *str,
12523 PyObject *substr,
12524 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012525 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012527 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12528 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012529 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012530 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531}
12532
INADA Naoki3ae20562017-01-16 20:41:20 +090012533/*[clinic input]
12534str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535
INADA Naoki3ae20562017-01-16 20:41:20 +090012536 old: unicode
12537 new: unicode
12538 count: Py_ssize_t = -1
12539 Maximum number of occurrences to replace.
12540 -1 (the default value) means replace all occurrences.
12541 /
12542
12543Return a copy with all occurrences of substring old replaced by new.
12544
12545If the optional argument count is given, only the first count occurrences are
12546replaced.
12547[clinic start generated code]*/
12548
12549static PyObject *
12550unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12551 Py_ssize_t count)
12552/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012553{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012554 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012555 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012556 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557}
12558
Alexander Belopolsky40018472011-02-26 01:02:56 +000012559static PyObject *
12560unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012562 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 Py_ssize_t isize;
12564 Py_ssize_t osize, squote, dquote, i, o;
12565 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012566 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012570 return NULL;
12571
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 isize = PyUnicode_GET_LENGTH(unicode);
12573 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 /* Compute length of output, quote characters, and
12576 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012577 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 max = 127;
12579 squote = dquote = 0;
12580 ikind = PyUnicode_KIND(unicode);
12581 for (i = 0; i < isize; i++) {
12582 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012583 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012585 case '\'': squote++; break;
12586 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012588 incr = 2;
12589 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 default:
12591 /* Fast-path ASCII */
12592 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012593 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012595 ;
12596 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012598 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012599 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012601 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012603 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012605 if (osize > PY_SSIZE_T_MAX - incr) {
12606 PyErr_SetString(PyExc_OverflowError,
12607 "string is too long to generate repr");
12608 return NULL;
12609 }
12610 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012611 }
12612
12613 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012614 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012615 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012616 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617 if (dquote)
12618 /* Both squote and dquote present. Use squote,
12619 and escape them */
12620 osize += squote;
12621 else
12622 quote = '"';
12623 }
Victor Stinner55c08782013-04-14 18:45:39 +020012624 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625
12626 repr = PyUnicode_New(osize, max);
12627 if (repr == NULL)
12628 return NULL;
12629 okind = PyUnicode_KIND(repr);
12630 odata = PyUnicode_DATA(repr);
12631
12632 PyUnicode_WRITE(okind, odata, 0, quote);
12633 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012634 if (unchanged) {
12635 _PyUnicode_FastCopyCharacters(repr, 1,
12636 unicode, 0,
12637 isize);
12638 }
12639 else {
12640 for (i = 0, o = 1; i < isize; i++) {
12641 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642
Victor Stinner55c08782013-04-14 18:45:39 +020012643 /* Escape quotes and backslashes */
12644 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012645 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012647 continue;
12648 }
12649
12650 /* Map special whitespace to '\t', \n', '\r' */
12651 if (ch == '\t') {
12652 PyUnicode_WRITE(okind, odata, o++, '\\');
12653 PyUnicode_WRITE(okind, odata, o++, 't');
12654 }
12655 else if (ch == '\n') {
12656 PyUnicode_WRITE(okind, odata, o++, '\\');
12657 PyUnicode_WRITE(okind, odata, o++, 'n');
12658 }
12659 else if (ch == '\r') {
12660 PyUnicode_WRITE(okind, odata, o++, '\\');
12661 PyUnicode_WRITE(okind, odata, o++, 'r');
12662 }
12663
12664 /* Map non-printable US ASCII to '\xhh' */
12665 else if (ch < ' ' || ch == 0x7F) {
12666 PyUnicode_WRITE(okind, odata, o++, '\\');
12667 PyUnicode_WRITE(okind, odata, o++, 'x');
12668 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12670 }
12671
12672 /* Copy ASCII characters as-is */
12673 else if (ch < 0x7F) {
12674 PyUnicode_WRITE(okind, odata, o++, ch);
12675 }
12676
12677 /* Non-ASCII characters */
12678 else {
12679 /* Map Unicode whitespace and control characters
12680 (categories Z* and C* except ASCII space)
12681 */
12682 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12683 PyUnicode_WRITE(okind, odata, o++, '\\');
12684 /* Map 8-bit characters to '\xhh' */
12685 if (ch <= 0xff) {
12686 PyUnicode_WRITE(okind, odata, o++, 'x');
12687 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12688 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12689 }
12690 /* Map 16-bit characters to '\uxxxx' */
12691 else if (ch <= 0xffff) {
12692 PyUnicode_WRITE(okind, odata, o++, 'u');
12693 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12694 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12695 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12696 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12697 }
12698 /* Map 21-bit characters to '\U00xxxxxx' */
12699 else {
12700 PyUnicode_WRITE(okind, odata, o++, 'U');
12701 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12702 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12703 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12704 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12705 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12706 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12707 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12708 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12709 }
12710 }
12711 /* Copy characters as-is */
12712 else {
12713 PyUnicode_WRITE(okind, odata, o++, ch);
12714 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012715 }
12716 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012717 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012718 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012719 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012720 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721}
12722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012723PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012724 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725\n\
12726Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012727such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728arguments start and end are interpreted as in slice notation.\n\
12729\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012730Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
12732static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012733unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012735 /* initialize variables to prevent gcc warning */
12736 PyObject *substring = NULL;
12737 Py_ssize_t start = 0;
12738 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012739 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012741 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012742 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012744 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012746
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012747 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012748
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012749 if (result == -2)
12750 return NULL;
12751
Christian Heimes217cfd12007-12-02 14:31:20 +000012752 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753}
12754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012755PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012756 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012758Return the highest index in S where substring sub is found,\n\
12759such that sub is contained within S[start:end]. Optional\n\
12760arguments start and end are interpreted as in slice notation.\n\
12761\n\
12762Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763
12764static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012767 /* initialize variables to prevent gcc warning */
12768 PyObject *substring = NULL;
12769 Py_ssize_t start = 0;
12770 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012771 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012773 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012774 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012776 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012778
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012779 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 if (result == -2)
12782 return NULL;
12783
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784 if (result < 0) {
12785 PyErr_SetString(PyExc_ValueError, "substring not found");
12786 return NULL;
12787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012788
Christian Heimes217cfd12007-12-02 14:31:20 +000012789 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790}
12791
INADA Naoki3ae20562017-01-16 20:41:20 +090012792/*[clinic input]
12793str.rjust as unicode_rjust
12794
12795 width: Py_ssize_t
12796 fillchar: Py_UCS4 = ' '
12797 /
12798
12799Return a right-justified string of length width.
12800
12801Padding is done using the specified fill character (default is a space).
12802[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
12804static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012805unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12806/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012808 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012809 return NULL;
12810
Victor Stinnerc4b49542011-12-11 22:44:26 +010012811 if (PyUnicode_GET_LENGTH(self) >= width)
12812 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813
Victor Stinnerc4b49542011-12-11 22:44:26 +010012814 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815}
12816
Alexander Belopolsky40018472011-02-26 01:02:56 +000012817PyObject *
12818PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012820 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012821 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012823 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824}
12825
INADA Naoki3ae20562017-01-16 20:41:20 +090012826/*[clinic input]
12827str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828
INADA Naoki3ae20562017-01-16 20:41:20 +090012829 sep: object = None
12830 The delimiter according which to split the string.
12831 None (the default value) means split according to any whitespace,
12832 and discard empty strings from the result.
12833 maxsplit: Py_ssize_t = -1
12834 Maximum number of splits to do.
12835 -1 (the default value) means no limit.
12836
12837Return a list of the words in the string, using sep as the delimiter string.
12838[clinic start generated code]*/
12839
12840static PyObject *
12841unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12842/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843{
INADA Naoki3ae20562017-01-16 20:41:20 +090012844 if (sep == Py_None)
12845 return split(self, NULL, maxsplit);
12846 if (PyUnicode_Check(sep))
12847 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012848
Victor Stinner998b8062018-09-12 00:23:25 +020012849 PyErr_Format(PyExc_TypeError,
12850 "must be str or None, not %.100s",
12851 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012852 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853}
12854
Thomas Wouters477c8d52006-05-27 19:21:47 +000012855PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012856PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012858 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012859 int kind1, kind2;
12860 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012861 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012862
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012863 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012864 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012865
Victor Stinner14f8f022011-10-05 20:58:25 +020012866 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868 len1 = PyUnicode_GET_LENGTH(str_obj);
12869 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012870 if (kind1 < kind2 || len1 < len2) {
12871 _Py_INCREF_UNICODE_EMPTY();
12872 if (!unicode_empty)
12873 out = NULL;
12874 else {
12875 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12876 Py_DECREF(unicode_empty);
12877 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012878 return out;
12879 }
12880 buf1 = PyUnicode_DATA(str_obj);
12881 buf2 = PyUnicode_DATA(sep_obj);
12882 if (kind2 != kind1) {
12883 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12884 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012885 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012886 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012887
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012888 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012889 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012890 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12891 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12892 else
12893 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012894 break;
12895 case PyUnicode_2BYTE_KIND:
12896 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12897 break;
12898 case PyUnicode_4BYTE_KIND:
12899 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12900 break;
12901 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012902 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012903 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012904
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012905 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012907
12908 return out;
12909}
12910
12911
12912PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012913PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012914{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012915 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012916 int kind1, kind2;
12917 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012918 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012919
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012920 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012921 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012922
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012923 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012925 len1 = PyUnicode_GET_LENGTH(str_obj);
12926 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012927 if (kind1 < kind2 || len1 < len2) {
12928 _Py_INCREF_UNICODE_EMPTY();
12929 if (!unicode_empty)
12930 out = NULL;
12931 else {
12932 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12933 Py_DECREF(unicode_empty);
12934 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012935 return out;
12936 }
12937 buf1 = PyUnicode_DATA(str_obj);
12938 buf2 = PyUnicode_DATA(sep_obj);
12939 if (kind2 != kind1) {
12940 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12941 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012942 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012943 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012945 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012946 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012947 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12948 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12949 else
12950 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 break;
12952 case PyUnicode_2BYTE_KIND:
12953 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12954 break;
12955 case PyUnicode_4BYTE_KIND:
12956 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12957 break;
12958 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012959 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012961
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012962 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012963 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012964
12965 return out;
12966}
12967
INADA Naoki3ae20562017-01-16 20:41:20 +090012968/*[clinic input]
12969str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970
INADA Naoki3ae20562017-01-16 20:41:20 +090012971 sep: object
12972 /
12973
12974Partition the string into three parts using the given separator.
12975
12976This will search for the separator in the string. If the separator is found,
12977returns a 3-tuple containing the part before the separator, the separator
12978itself, and the part after it.
12979
12980If the separator is not found, returns a 3-tuple containing the original string
12981and two empty strings.
12982[clinic start generated code]*/
12983
12984static PyObject *
12985unicode_partition(PyObject *self, PyObject *sep)
12986/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012987{
INADA Naoki3ae20562017-01-16 20:41:20 +090012988 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012989}
12990
INADA Naoki3ae20562017-01-16 20:41:20 +090012991/*[clinic input]
12992str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012993
INADA Naoki3ae20562017-01-16 20:41:20 +090012994Partition the string into three parts using the given separator.
12995
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012996This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012997the separator is found, returns a 3-tuple containing the part before the
12998separator, the separator itself, and the part after it.
12999
13000If the separator is not found, returns a 3-tuple containing two empty strings
13001and the original string.
13002[clinic start generated code]*/
13003
13004static PyObject *
13005unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013006/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013007{
INADA Naoki3ae20562017-01-16 20:41:20 +090013008 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013009}
13010
Alexander Belopolsky40018472011-02-26 01:02:56 +000013011PyObject *
13012PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013013{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013014 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013015 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013016
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013017 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013018}
13019
INADA Naoki3ae20562017-01-16 20:41:20 +090013020/*[clinic input]
13021str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013022
INADA Naoki3ae20562017-01-16 20:41:20 +090013023Return a list of the words in the string, using sep as the delimiter string.
13024
13025Splits are done starting at the end of the string and working to the front.
13026[clinic start generated code]*/
13027
13028static PyObject *
13029unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13030/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013031{
INADA Naoki3ae20562017-01-16 20:41:20 +090013032 if (sep == Py_None)
13033 return rsplit(self, NULL, maxsplit);
13034 if (PyUnicode_Check(sep))
13035 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013036
Victor Stinner998b8062018-09-12 00:23:25 +020013037 PyErr_Format(PyExc_TypeError,
13038 "must be str or None, not %.100s",
13039 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013040 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013041}
13042
INADA Naoki3ae20562017-01-16 20:41:20 +090013043/*[clinic input]
13044str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013045
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013046 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013047
13048Return a list of the lines in the string, breaking at line boundaries.
13049
13050Line breaks are not included in the resulting list unless keepends is given and
13051true.
13052[clinic start generated code]*/
13053
13054static PyObject *
13055unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013056/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013058 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059}
13060
13061static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013062PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013063{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013064 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065}
13066
INADA Naoki3ae20562017-01-16 20:41:20 +090013067/*[clinic input]
13068str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069
INADA Naoki3ae20562017-01-16 20:41:20 +090013070Convert uppercase characters to lowercase and lowercase characters to uppercase.
13071[clinic start generated code]*/
13072
13073static PyObject *
13074unicode_swapcase_impl(PyObject *self)
13075/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013076{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013077 if (PyUnicode_READY(self) == -1)
13078 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013079 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013080}
13081
Larry Hastings61272b72014-01-07 12:41:53 -080013082/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013083
Larry Hastings31826802013-10-19 00:09:25 -070013084@staticmethod
13085str.maketrans as unicode_maketrans
13086
13087 x: object
13088
13089 y: unicode=NULL
13090
13091 z: unicode=NULL
13092
13093 /
13094
13095Return a translation table usable for str.translate().
13096
13097If there is only one argument, it must be a dictionary mapping Unicode
13098ordinals (integers) or characters to Unicode ordinals, strings or None.
13099Character keys will be then converted to ordinals.
13100If there are two arguments, they must be strings of equal length, and
13101in the resulting dictionary, each character in x will be mapped to the
13102character at the same position in y. If there is a third argument, it
13103must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013104[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013105
Larry Hastings31826802013-10-19 00:09:25 -070013106static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013107unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013108/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013109{
Georg Brandlceee0772007-11-27 23:48:05 +000013110 PyObject *new = NULL, *key, *value;
13111 Py_ssize_t i = 0;
13112 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013113
Georg Brandlceee0772007-11-27 23:48:05 +000013114 new = PyDict_New();
13115 if (!new)
13116 return NULL;
13117 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 int x_kind, y_kind, z_kind;
13119 void *x_data, *y_data, *z_data;
13120
Georg Brandlceee0772007-11-27 23:48:05 +000013121 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013122 if (!PyUnicode_Check(x)) {
13123 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13124 "be a string if there is a second argument");
13125 goto err;
13126 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013128 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13129 "arguments must have equal length");
13130 goto err;
13131 }
13132 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 x_kind = PyUnicode_KIND(x);
13134 y_kind = PyUnicode_KIND(y);
13135 x_data = PyUnicode_DATA(x);
13136 y_data = PyUnicode_DATA(y);
13137 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13138 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013139 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013140 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013141 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013142 if (!value) {
13143 Py_DECREF(key);
13144 goto err;
13145 }
Georg Brandlceee0772007-11-27 23:48:05 +000013146 res = PyDict_SetItem(new, key, value);
13147 Py_DECREF(key);
13148 Py_DECREF(value);
13149 if (res < 0)
13150 goto err;
13151 }
13152 /* create entries for deleting chars in z */
13153 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013154 z_kind = PyUnicode_KIND(z);
13155 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013156 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013158 if (!key)
13159 goto err;
13160 res = PyDict_SetItem(new, key, Py_None);
13161 Py_DECREF(key);
13162 if (res < 0)
13163 goto err;
13164 }
13165 }
13166 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013167 int kind;
13168 void *data;
13169
Georg Brandlceee0772007-11-27 23:48:05 +000013170 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013171 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013172 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13173 "to maketrans it must be a dict");
13174 goto err;
13175 }
13176 /* copy entries into the new dict, converting string keys to int keys */
13177 while (PyDict_Next(x, &i, &key, &value)) {
13178 if (PyUnicode_Check(key)) {
13179 /* convert string keys to integer keys */
13180 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013181 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013182 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13183 "table must be of length 1");
13184 goto err;
13185 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013186 kind = PyUnicode_KIND(key);
13187 data = PyUnicode_DATA(key);
13188 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013189 if (!newkey)
13190 goto err;
13191 res = PyDict_SetItem(new, newkey, value);
13192 Py_DECREF(newkey);
13193 if (res < 0)
13194 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013195 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013196 /* just keep integer keys */
13197 if (PyDict_SetItem(new, key, value) < 0)
13198 goto err;
13199 } else {
13200 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13201 "be strings or integers");
13202 goto err;
13203 }
13204 }
13205 }
13206 return new;
13207 err:
13208 Py_DECREF(new);
13209 return NULL;
13210}
13211
INADA Naoki3ae20562017-01-16 20:41:20 +090013212/*[clinic input]
13213str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214
INADA Naoki3ae20562017-01-16 20:41:20 +090013215 table: object
13216 Translation table, which must be a mapping of Unicode ordinals to
13217 Unicode ordinals, strings, or None.
13218 /
13219
13220Replace each character in the string using the given translation table.
13221
13222The table must implement lookup/indexing via __getitem__, for instance a
13223dictionary or list. If this operation raises LookupError, the character is
13224left untouched. Characters mapped to None are deleted.
13225[clinic start generated code]*/
13226
13227static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013228unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013229/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013231 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232}
13233
INADA Naoki3ae20562017-01-16 20:41:20 +090013234/*[clinic input]
13235str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236
INADA Naoki3ae20562017-01-16 20:41:20 +090013237Return a copy of the string converted to uppercase.
13238[clinic start generated code]*/
13239
13240static PyObject *
13241unicode_upper_impl(PyObject *self)
13242/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013243{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013244 if (PyUnicode_READY(self) == -1)
13245 return NULL;
13246 if (PyUnicode_IS_ASCII(self))
13247 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013248 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249}
13250
INADA Naoki3ae20562017-01-16 20:41:20 +090013251/*[clinic input]
13252str.zfill as unicode_zfill
13253
13254 width: Py_ssize_t
13255 /
13256
13257Pad a numeric string with zeros on the left, to fill a field of the given width.
13258
13259The string is never truncated.
13260[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261
13262static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013263unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013264/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013266 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013267 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013268 int kind;
13269 void *data;
13270 Py_UCS4 chr;
13271
Benjamin Petersonbac79492012-01-14 13:34:47 -050013272 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013273 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274
Victor Stinnerc4b49542011-12-11 22:44:26 +010013275 if (PyUnicode_GET_LENGTH(self) >= width)
13276 return unicode_result_unchanged(self);
13277
13278 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013279
13280 u = pad(self, fill, 0, '0');
13281
Walter Dörwald068325e2002-04-15 13:36:47 +000013282 if (u == NULL)
13283 return NULL;
13284
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013285 kind = PyUnicode_KIND(u);
13286 data = PyUnicode_DATA(u);
13287 chr = PyUnicode_READ(kind, data, fill);
13288
13289 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 PyUnicode_WRITE(kind, data, 0, chr);
13292 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293 }
13294
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013295 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013296 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013297}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013298
13299#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013300static PyObject *
13301unicode__decimal2ascii(PyObject *self)
13302{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013303 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013304}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013305#endif
13306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013307PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013308 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013309\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013310Return True if S starts with the specified prefix, False otherwise.\n\
13311With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013312With optional end, stop comparing S at that position.\n\
13313prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013314
13315static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013316unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013317 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013318{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013319 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013320 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013321 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013322 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013323 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013324
Jesus Ceaac451502011-04-20 17:09:23 +020013325 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013326 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013327 if (PyTuple_Check(subobj)) {
13328 Py_ssize_t i;
13329 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013330 substring = PyTuple_GET_ITEM(subobj, i);
13331 if (!PyUnicode_Check(substring)) {
13332 PyErr_Format(PyExc_TypeError,
13333 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013334 "not %.100s",
13335 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013336 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013337 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013338 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013339 if (result == -1)
13340 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013341 if (result) {
13342 Py_RETURN_TRUE;
13343 }
13344 }
13345 /* nothing matched */
13346 Py_RETURN_FALSE;
13347 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013348 if (!PyUnicode_Check(subobj)) {
13349 PyErr_Format(PyExc_TypeError,
13350 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013351 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013353 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013354 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013355 if (result == -1)
13356 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013357 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358}
13359
13360
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013361PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013363\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013364Return True if S ends with the specified suffix, False otherwise.\n\
13365With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013366With optional end, stop comparing S at that position.\n\
13367suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013368
13369static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013370unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013372{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013373 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013374 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013375 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013376 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013377 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013378
Jesus Ceaac451502011-04-20 17:09:23 +020013379 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013381 if (PyTuple_Check(subobj)) {
13382 Py_ssize_t i;
13383 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013384 substring = PyTuple_GET_ITEM(subobj, i);
13385 if (!PyUnicode_Check(substring)) {
13386 PyErr_Format(PyExc_TypeError,
13387 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013388 "not %.100s",
13389 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013390 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013391 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013392 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013393 if (result == -1)
13394 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013395 if (result) {
13396 Py_RETURN_TRUE;
13397 }
13398 }
13399 Py_RETURN_FALSE;
13400 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013401 if (!PyUnicode_Check(subobj)) {
13402 PyErr_Format(PyExc_TypeError,
13403 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013404 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013406 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013407 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013408 if (result == -1)
13409 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013410 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013411}
13412
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013413static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013414_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013415{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013416 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13417 writer->data = PyUnicode_DATA(writer->buffer);
13418
13419 if (!writer->readonly) {
13420 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013421 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013422 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013423 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013424 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13425 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13426 writer->kind = PyUnicode_WCHAR_KIND;
13427 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13428
Victor Stinner8f674cc2013-04-17 23:02:17 +020013429 /* Copy-on-write mode: set buffer size to 0 so
13430 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13431 * next write. */
13432 writer->size = 0;
13433 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013434}
13435
Victor Stinnerd3f08822012-05-29 12:57:52 +020013436void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013437_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013438{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013439 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013440
13441 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013442 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013443
13444 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13445 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13446 writer->kind = PyUnicode_WCHAR_KIND;
13447 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013448}
13449
Victor Stinnerd3f08822012-05-29 12:57:52 +020013450int
13451_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13452 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013453{
13454 Py_ssize_t newlen;
13455 PyObject *newbuffer;
13456
Victor Stinner2740e462016-09-06 16:58:36 -070013457 assert(maxchar <= MAX_UNICODE);
13458
Victor Stinnerca9381e2015-09-22 00:58:32 +020013459 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013460 assert((maxchar > writer->maxchar && length >= 0)
13461 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013462
Victor Stinner202fdca2012-05-07 12:47:02 +020013463 if (length > PY_SSIZE_T_MAX - writer->pos) {
13464 PyErr_NoMemory();
13465 return -1;
13466 }
13467 newlen = writer->pos + length;
13468
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013469 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013470
Victor Stinnerd3f08822012-05-29 12:57:52 +020013471 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013472 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013473 if (writer->overallocate
13474 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13475 /* overallocate to limit the number of realloc() */
13476 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013477 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013478 if (newlen < writer->min_length)
13479 newlen = writer->min_length;
13480
Victor Stinnerd3f08822012-05-29 12:57:52 +020013481 writer->buffer = PyUnicode_New(newlen, maxchar);
13482 if (writer->buffer == NULL)
13483 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013484 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013485 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013486 if (writer->overallocate
13487 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13488 /* overallocate to limit the number of realloc() */
13489 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013490 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013491 if (newlen < writer->min_length)
13492 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013493
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013494 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013495 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013496 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013497 newbuffer = PyUnicode_New(newlen, maxchar);
13498 if (newbuffer == NULL)
13499 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013500 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13501 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013502 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013503 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013504 }
13505 else {
13506 newbuffer = resize_compact(writer->buffer, newlen);
13507 if (newbuffer == NULL)
13508 return -1;
13509 }
13510 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013511 }
13512 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013513 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013514 newbuffer = PyUnicode_New(writer->size, maxchar);
13515 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013516 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13518 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013519 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013520 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013521 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013522 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013523
13524#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013525}
13526
Victor Stinnerca9381e2015-09-22 00:58:32 +020013527int
13528_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13529 enum PyUnicode_Kind kind)
13530{
13531 Py_UCS4 maxchar;
13532
13533 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13534 assert(writer->kind < kind);
13535
13536 switch (kind)
13537 {
13538 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13539 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13540 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13541 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013542 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013543 }
13544
13545 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13546}
13547
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013548static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013549_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013550{
Victor Stinner2740e462016-09-06 16:58:36 -070013551 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013552 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13553 return -1;
13554 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13555 writer->pos++;
13556 return 0;
13557}
13558
13559int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013560_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13561{
13562 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13563}
13564
13565int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013566_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13567{
13568 Py_UCS4 maxchar;
13569 Py_ssize_t len;
13570
13571 if (PyUnicode_READY(str) == -1)
13572 return -1;
13573 len = PyUnicode_GET_LENGTH(str);
13574 if (len == 0)
13575 return 0;
13576 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13577 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013578 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013579 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013580 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013581 Py_INCREF(str);
13582 writer->buffer = str;
13583 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013584 writer->pos += len;
13585 return 0;
13586 }
13587 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13588 return -1;
13589 }
13590 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13591 str, 0, len);
13592 writer->pos += len;
13593 return 0;
13594}
13595
Victor Stinnere215d962012-10-06 23:03:36 +020013596int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013597_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13598 Py_ssize_t start, Py_ssize_t end)
13599{
13600 Py_UCS4 maxchar;
13601 Py_ssize_t len;
13602
13603 if (PyUnicode_READY(str) == -1)
13604 return -1;
13605
13606 assert(0 <= start);
13607 assert(end <= PyUnicode_GET_LENGTH(str));
13608 assert(start <= end);
13609
13610 if (end == 0)
13611 return 0;
13612
13613 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13614 return _PyUnicodeWriter_WriteStr(writer, str);
13615
13616 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13617 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13618 else
13619 maxchar = writer->maxchar;
13620 len = end - start;
13621
13622 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13623 return -1;
13624
13625 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13626 str, start, len);
13627 writer->pos += len;
13628 return 0;
13629}
13630
13631int
Victor Stinner4a587072013-11-19 12:54:53 +010013632_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13633 const char *ascii, Py_ssize_t len)
13634{
13635 if (len == -1)
13636 len = strlen(ascii);
13637
13638 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13639
13640 if (writer->buffer == NULL && !writer->overallocate) {
13641 PyObject *str;
13642
13643 str = _PyUnicode_FromASCII(ascii, len);
13644 if (str == NULL)
13645 return -1;
13646
13647 writer->readonly = 1;
13648 writer->buffer = str;
13649 _PyUnicodeWriter_Update(writer);
13650 writer->pos += len;
13651 return 0;
13652 }
13653
13654 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13655 return -1;
13656
13657 switch (writer->kind)
13658 {
13659 case PyUnicode_1BYTE_KIND:
13660 {
13661 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13662 Py_UCS1 *data = writer->data;
13663
Christian Heimesf051e432016-09-13 20:22:02 +020013664 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013665 break;
13666 }
13667 case PyUnicode_2BYTE_KIND:
13668 {
13669 _PyUnicode_CONVERT_BYTES(
13670 Py_UCS1, Py_UCS2,
13671 ascii, ascii + len,
13672 (Py_UCS2 *)writer->data + writer->pos);
13673 break;
13674 }
13675 case PyUnicode_4BYTE_KIND:
13676 {
13677 _PyUnicode_CONVERT_BYTES(
13678 Py_UCS1, Py_UCS4,
13679 ascii, ascii + len,
13680 (Py_UCS4 *)writer->data + writer->pos);
13681 break;
13682 }
13683 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013684 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013685 }
13686
13687 writer->pos += len;
13688 return 0;
13689}
13690
13691int
13692_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13693 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013694{
13695 Py_UCS4 maxchar;
13696
13697 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13698 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13699 return -1;
13700 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13701 writer->pos += len;
13702 return 0;
13703}
13704
Victor Stinnerd3f08822012-05-29 12:57:52 +020013705PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013706_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013707{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013708 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013709
Victor Stinnerd3f08822012-05-29 12:57:52 +020013710 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013711 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013712 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013713 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013714
13715 str = writer->buffer;
13716 writer->buffer = NULL;
13717
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013718 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013719 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13720 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013721 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013722
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013723 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13724 PyObject *str2;
13725 str2 = resize_compact(str, writer->pos);
13726 if (str2 == NULL) {
13727 Py_DECREF(str);
13728 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013729 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013730 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013731 }
13732
Victor Stinner15a0bd32013-07-08 22:29:55 +020013733 assert(_PyUnicode_CheckConsistency(str, 1));
13734 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013735}
13736
Victor Stinnerd3f08822012-05-29 12:57:52 +020013737void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013738_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013739{
13740 Py_CLEAR(writer->buffer);
13741}
13742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013743#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013744
13745PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013746 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013747\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013748Return a formatted version of S, using substitutions from args and kwargs.\n\
13749The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013750
Eric Smith27bbca62010-11-04 17:06:58 +000013751PyDoc_STRVAR(format_map__doc__,
13752 "S.format_map(mapping) -> str\n\
13753\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013754Return a formatted version of S, using substitutions from mapping.\n\
13755The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013756
INADA Naoki3ae20562017-01-16 20:41:20 +090013757/*[clinic input]
13758str.__format__ as unicode___format__
13759
13760 format_spec: unicode
13761 /
13762
13763Return a formatted version of the string as described by format_spec.
13764[clinic start generated code]*/
13765
Eric Smith4a7d76d2008-05-30 18:10:19 +000013766static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013767unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013768/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013769{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013770 _PyUnicodeWriter writer;
13771 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013772
Victor Stinnerd3f08822012-05-29 12:57:52 +020013773 if (PyUnicode_READY(self) == -1)
13774 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013775 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013776 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13777 self, format_spec, 0,
13778 PyUnicode_GET_LENGTH(format_spec));
13779 if (ret == -1) {
13780 _PyUnicodeWriter_Dealloc(&writer);
13781 return NULL;
13782 }
13783 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013784}
13785
INADA Naoki3ae20562017-01-16 20:41:20 +090013786/*[clinic input]
13787str.__sizeof__ as unicode_sizeof
13788
13789Return the size of the string in memory, in bytes.
13790[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013791
13792static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013793unicode_sizeof_impl(PyObject *self)
13794/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796 Py_ssize_t size;
13797
13798 /* If it's a compact object, account for base structure +
13799 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013800 if (PyUnicode_IS_COMPACT_ASCII(self))
13801 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13802 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013803 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013804 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013805 else {
13806 /* If it is a two-block object, account for base object, and
13807 for character block if present. */
13808 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013809 if (_PyUnicode_DATA_ANY(self))
13810 size += (PyUnicode_GET_LENGTH(self) + 1) *
13811 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013812 }
13813 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013814 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013815 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13816 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13817 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13818 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013819
13820 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013821}
13822
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013823static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013824unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013825{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013826 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013827 if (!copy)
13828 return NULL;
13829 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013830}
13831
Guido van Rossumd57fd912000-03-10 22:53:23 +000013832static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013833 UNICODE_ENCODE_METHODDEF
13834 UNICODE_REPLACE_METHODDEF
13835 UNICODE_SPLIT_METHODDEF
13836 UNICODE_RSPLIT_METHODDEF
13837 UNICODE_JOIN_METHODDEF
13838 UNICODE_CAPITALIZE_METHODDEF
13839 UNICODE_CASEFOLD_METHODDEF
13840 UNICODE_TITLE_METHODDEF
13841 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013842 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013843 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013844 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013845 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013846 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013847 UNICODE_LJUST_METHODDEF
13848 UNICODE_LOWER_METHODDEF
13849 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013850 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13851 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013852 UNICODE_RJUST_METHODDEF
13853 UNICODE_RSTRIP_METHODDEF
13854 UNICODE_RPARTITION_METHODDEF
13855 UNICODE_SPLITLINES_METHODDEF
13856 UNICODE_STRIP_METHODDEF
13857 UNICODE_SWAPCASE_METHODDEF
13858 UNICODE_TRANSLATE_METHODDEF
13859 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013860 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13861 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013862 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013863 UNICODE_ISLOWER_METHODDEF
13864 UNICODE_ISUPPER_METHODDEF
13865 UNICODE_ISTITLE_METHODDEF
13866 UNICODE_ISSPACE_METHODDEF
13867 UNICODE_ISDECIMAL_METHODDEF
13868 UNICODE_ISDIGIT_METHODDEF
13869 UNICODE_ISNUMERIC_METHODDEF
13870 UNICODE_ISALPHA_METHODDEF
13871 UNICODE_ISALNUM_METHODDEF
13872 UNICODE_ISIDENTIFIER_METHODDEF
13873 UNICODE_ISPRINTABLE_METHODDEF
13874 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013875 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013876 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013877 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013878 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013879 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013880#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013881 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013882 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013883#endif
13884
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013885 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886 {NULL, NULL}
13887};
13888
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013889static PyObject *
13890unicode_mod(PyObject *v, PyObject *w)
13891{
Brian Curtindfc80e32011-08-10 20:28:54 -050013892 if (!PyUnicode_Check(v))
13893 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013894 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013895}
13896
13897static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013898 0, /*nb_add*/
13899 0, /*nb_subtract*/
13900 0, /*nb_multiply*/
13901 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013902};
13903
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013905 (lenfunc) unicode_length, /* sq_length */
13906 PyUnicode_Concat, /* sq_concat */
13907 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13908 (ssizeargfunc) unicode_getitem, /* sq_item */
13909 0, /* sq_slice */
13910 0, /* sq_ass_item */
13911 0, /* sq_ass_slice */
13912 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013913};
13914
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013915static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013916unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013918 if (PyUnicode_READY(self) == -1)
13919 return NULL;
13920
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013921 if (PyIndex_Check(item)) {
13922 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013923 if (i == -1 && PyErr_Occurred())
13924 return NULL;
13925 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013926 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013927 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013928 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013929 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013930 PyObject *result;
13931 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013932 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013933 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013934
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013935 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013936 return NULL;
13937 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013938 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13939 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013940
13941 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013942 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013943 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013944 slicelength == PyUnicode_GET_LENGTH(self)) {
13945 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013946 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013947 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013948 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013949 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013950 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013951 src_kind = PyUnicode_KIND(self);
13952 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013953 if (!PyUnicode_IS_ASCII(self)) {
13954 kind_limit = kind_maxchar_limit(src_kind);
13955 max_char = 0;
13956 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13957 ch = PyUnicode_READ(src_kind, src_data, cur);
13958 if (ch > max_char) {
13959 max_char = ch;
13960 if (max_char >= kind_limit)
13961 break;
13962 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013963 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013964 }
Victor Stinner55c99112011-10-13 01:17:06 +020013965 else
13966 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013967 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013968 if (result == NULL)
13969 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013970 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013971 dest_data = PyUnicode_DATA(result);
13972
13973 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013974 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13975 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013976 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013977 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013978 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013979 } else {
13980 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13981 return NULL;
13982 }
13983}
13984
13985static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013986 (lenfunc)unicode_length, /* mp_length */
13987 (binaryfunc)unicode_subscript, /* mp_subscript */
13988 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013989};
13990
Guido van Rossumd57fd912000-03-10 22:53:23 +000013991
Guido van Rossumd57fd912000-03-10 22:53:23 +000013992/* Helpers for PyUnicode_Format() */
13993
Victor Stinnera47082312012-10-04 02:19:54 +020013994struct unicode_formatter_t {
13995 PyObject *args;
13996 int args_owned;
13997 Py_ssize_t arglen, argidx;
13998 PyObject *dict;
13999
14000 enum PyUnicode_Kind fmtkind;
14001 Py_ssize_t fmtcnt, fmtpos;
14002 void *fmtdata;
14003 PyObject *fmtstr;
14004
14005 _PyUnicodeWriter writer;
14006};
14007
14008struct unicode_format_arg_t {
14009 Py_UCS4 ch;
14010 int flags;
14011 Py_ssize_t width;
14012 int prec;
14013 int sign;
14014};
14015
Guido van Rossumd57fd912000-03-10 22:53:23 +000014016static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014017unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014018{
Victor Stinnera47082312012-10-04 02:19:54 +020014019 Py_ssize_t argidx = ctx->argidx;
14020
14021 if (argidx < ctx->arglen) {
14022 ctx->argidx++;
14023 if (ctx->arglen < 0)
14024 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014025 else
Victor Stinnera47082312012-10-04 02:19:54 +020014026 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014027 }
14028 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014029 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014030 return NULL;
14031}
14032
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014033/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014034
Victor Stinnera47082312012-10-04 02:19:54 +020014035/* Format a float into the writer if the writer is not NULL, or into *p_output
14036 otherwise.
14037
14038 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014039static int
Victor Stinnera47082312012-10-04 02:19:54 +020014040formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14041 PyObject **p_output,
14042 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014043{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014044 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014045 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014046 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014047 int prec;
14048 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014049
Guido van Rossumd57fd912000-03-10 22:53:23 +000014050 x = PyFloat_AsDouble(v);
14051 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014052 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014053
Victor Stinnera47082312012-10-04 02:19:54 +020014054 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014055 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014056 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014057
Victor Stinnera47082312012-10-04 02:19:54 +020014058 if (arg->flags & F_ALT)
14059 dtoa_flags = Py_DTSF_ALT;
14060 else
14061 dtoa_flags = 0;
14062 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014063 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014064 return -1;
14065 len = strlen(p);
14066 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014067 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014068 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014069 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014070 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014071 }
14072 else
14073 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014074 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014075 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014076}
14077
Victor Stinnerd0880d52012-04-27 23:40:13 +020014078/* formatlong() emulates the format codes d, u, o, x and X, and
14079 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14080 * Python's regular ints.
14081 * Return value: a new PyUnicodeObject*, or NULL if error.
14082 * The output string is of the form
14083 * "-"? ("0x" | "0X")? digit+
14084 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14085 * set in flags. The case of hex digits will be correct,
14086 * There will be at least prec digits, zero-filled on the left if
14087 * necessary to get that many.
14088 * val object to be converted
14089 * flags bitmask of format flags; only F_ALT is looked at
14090 * prec minimum number of digits; 0-fill on left if needed
14091 * type a character in [duoxX]; u acts the same as d
14092 *
14093 * CAUTION: o, x and X conversions on regular ints can never
14094 * produce a '-' sign, but can for Python's unbounded ints.
14095 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014096PyObject *
14097_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014098{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014099 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014101 Py_ssize_t i;
14102 int sign; /* 1 if '-', else 0 */
14103 int len; /* number of characters */
14104 Py_ssize_t llen;
14105 int numdigits; /* len == numnondigits + numdigits */
14106 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014107
Victor Stinnerd0880d52012-04-27 23:40:13 +020014108 /* Avoid exceeding SSIZE_T_MAX */
14109 if (prec > INT_MAX-3) {
14110 PyErr_SetString(PyExc_OverflowError,
14111 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014113 }
14114
14115 assert(PyLong_Check(val));
14116
14117 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014118 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014119 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014120 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014121 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014122 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014123 /* int and int subclasses should print numerically when a numeric */
14124 /* format code is used (see issue18780) */
14125 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014126 break;
14127 case 'o':
14128 numnondigits = 2;
14129 result = PyNumber_ToBase(val, 8);
14130 break;
14131 case 'x':
14132 case 'X':
14133 numnondigits = 2;
14134 result = PyNumber_ToBase(val, 16);
14135 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014136 }
14137 if (!result)
14138 return NULL;
14139
14140 assert(unicode_modifiable(result));
14141 assert(PyUnicode_IS_READY(result));
14142 assert(PyUnicode_IS_ASCII(result));
14143
14144 /* To modify the string in-place, there can only be one reference. */
14145 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014146 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014147 PyErr_BadInternalCall();
14148 return NULL;
14149 }
14150 buf = PyUnicode_DATA(result);
14151 llen = PyUnicode_GET_LENGTH(result);
14152 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014153 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014154 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014155 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014156 return NULL;
14157 }
14158 len = (int)llen;
14159 sign = buf[0] == '-';
14160 numnondigits += sign;
14161 numdigits = len - numnondigits;
14162 assert(numdigits > 0);
14163
14164 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014165 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014166 (type == 'o' || type == 'x' || type == 'X'))) {
14167 assert(buf[sign] == '0');
14168 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14169 buf[sign+1] == 'o');
14170 numnondigits -= 2;
14171 buf += 2;
14172 len -= 2;
14173 if (sign)
14174 buf[0] = '-';
14175 assert(len == numnondigits + numdigits);
14176 assert(numdigits > 0);
14177 }
14178
14179 /* Fill with leading zeroes to meet minimum width. */
14180 if (prec > numdigits) {
14181 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14182 numnondigits + prec);
14183 char *b1;
14184 if (!r1) {
14185 Py_DECREF(result);
14186 return NULL;
14187 }
14188 b1 = PyBytes_AS_STRING(r1);
14189 for (i = 0; i < numnondigits; ++i)
14190 *b1++ = *buf++;
14191 for (i = 0; i < prec - numdigits; i++)
14192 *b1++ = '0';
14193 for (i = 0; i < numdigits; i++)
14194 *b1++ = *buf++;
14195 *b1 = '\0';
14196 Py_DECREF(result);
14197 result = r1;
14198 buf = PyBytes_AS_STRING(result);
14199 len = numnondigits + prec;
14200 }
14201
14202 /* Fix up case for hex conversions. */
14203 if (type == 'X') {
14204 /* Need to convert all lower case letters to upper case.
14205 and need to convert 0x to 0X (and -0x to -0X). */
14206 for (i = 0; i < len; i++)
14207 if (buf[i] >= 'a' && buf[i] <= 'x')
14208 buf[i] -= 'a'-'A';
14209 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210 if (!PyUnicode_Check(result)
14211 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014212 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014213 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014214 Py_DECREF(result);
14215 result = unicode;
14216 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014217 else if (len != PyUnicode_GET_LENGTH(result)) {
14218 if (PyUnicode_Resize(&result, len) < 0)
14219 Py_CLEAR(result);
14220 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014221 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014222}
14223
Ethan Furmandf3ed242014-01-05 06:50:30 -080014224/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014225 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014226 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014227 * -1 and raise an exception on error */
14228static int
Victor Stinnera47082312012-10-04 02:19:54 +020014229mainformatlong(PyObject *v,
14230 struct unicode_format_arg_t *arg,
14231 PyObject **p_output,
14232 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014233{
14234 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014235 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014236
14237 if (!PyNumber_Check(v))
14238 goto wrongtype;
14239
Ethan Furman9ab74802014-03-21 06:38:46 -070014240 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014241 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014242 if (type == 'o' || type == 'x' || type == 'X') {
14243 iobj = PyNumber_Index(v);
14244 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014245 if (PyErr_ExceptionMatches(PyExc_TypeError))
14246 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014247 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014248 }
14249 }
14250 else {
14251 iobj = PyNumber_Long(v);
14252 if (iobj == NULL ) {
14253 if (PyErr_ExceptionMatches(PyExc_TypeError))
14254 goto wrongtype;
14255 return -1;
14256 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014257 }
14258 assert(PyLong_Check(iobj));
14259 }
14260 else {
14261 iobj = v;
14262 Py_INCREF(iobj);
14263 }
14264
14265 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014266 && arg->width == -1 && arg->prec == -1
14267 && !(arg->flags & (F_SIGN | F_BLANK))
14268 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014269 {
14270 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014271 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014272 int base;
14273
Victor Stinnera47082312012-10-04 02:19:54 +020014274 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014275 {
14276 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014277 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014278 case 'd':
14279 case 'i':
14280 case 'u':
14281 base = 10;
14282 break;
14283 case 'o':
14284 base = 8;
14285 break;
14286 case 'x':
14287 case 'X':
14288 base = 16;
14289 break;
14290 }
14291
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014292 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14293 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014294 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014295 }
14296 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014297 return 1;
14298 }
14299
Ethan Furmanb95b5612015-01-23 20:05:18 -080014300 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014301 Py_DECREF(iobj);
14302 if (res == NULL)
14303 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014304 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014305 return 0;
14306
14307wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014308 switch(type)
14309 {
14310 case 'o':
14311 case 'x':
14312 case 'X':
14313 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014314 "%%%c format: an integer is required, "
14315 "not %.200s",
14316 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014317 break;
14318 default:
14319 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014320 "%%%c format: a number is required, "
14321 "not %.200s",
14322 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014323 break;
14324 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014325 return -1;
14326}
14327
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014328static Py_UCS4
14329formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014330{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014331 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014332 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014333 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014334 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014335 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014336 goto onError;
14337 }
14338 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014339 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014340 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014341 /* make sure number is a type of integer */
14342 if (!PyLong_Check(v)) {
14343 iobj = PyNumber_Index(v);
14344 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014345 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014346 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014347 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014348 Py_DECREF(iobj);
14349 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014350 else {
14351 x = PyLong_AsLong(v);
14352 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014353 if (x == -1 && PyErr_Occurred())
14354 goto onError;
14355
Victor Stinner8faf8212011-12-08 22:14:11 +010014356 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014357 PyErr_SetString(PyExc_OverflowError,
14358 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014359 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014360 }
14361
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014362 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014363 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014364
Benjamin Peterson29060642009-01-31 22:14:21 +000014365 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014366 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014367 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014368 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014369}
14370
Victor Stinnera47082312012-10-04 02:19:54 +020014371/* Parse options of an argument: flags, width, precision.
14372 Handle also "%(name)" syntax.
14373
14374 Return 0 if the argument has been formatted into arg->str.
14375 Return 1 if the argument has been written into ctx->writer,
14376 Raise an exception and return -1 on error. */
14377static int
14378unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14379 struct unicode_format_arg_t *arg)
14380{
14381#define FORMAT_READ(ctx) \
14382 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14383
14384 PyObject *v;
14385
Victor Stinnera47082312012-10-04 02:19:54 +020014386 if (arg->ch == '(') {
14387 /* Get argument value from a dictionary. Example: "%(name)s". */
14388 Py_ssize_t keystart;
14389 Py_ssize_t keylen;
14390 PyObject *key;
14391 int pcount = 1;
14392
14393 if (ctx->dict == NULL) {
14394 PyErr_SetString(PyExc_TypeError,
14395 "format requires a mapping");
14396 return -1;
14397 }
14398 ++ctx->fmtpos;
14399 --ctx->fmtcnt;
14400 keystart = ctx->fmtpos;
14401 /* Skip over balanced parentheses */
14402 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14403 arg->ch = FORMAT_READ(ctx);
14404 if (arg->ch == ')')
14405 --pcount;
14406 else if (arg->ch == '(')
14407 ++pcount;
14408 ctx->fmtpos++;
14409 }
14410 keylen = ctx->fmtpos - keystart - 1;
14411 if (ctx->fmtcnt < 0 || pcount > 0) {
14412 PyErr_SetString(PyExc_ValueError,
14413 "incomplete format key");
14414 return -1;
14415 }
14416 key = PyUnicode_Substring(ctx->fmtstr,
14417 keystart, keystart + keylen);
14418 if (key == NULL)
14419 return -1;
14420 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014421 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014422 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014423 }
14424 ctx->args = PyObject_GetItem(ctx->dict, key);
14425 Py_DECREF(key);
14426 if (ctx->args == NULL)
14427 return -1;
14428 ctx->args_owned = 1;
14429 ctx->arglen = -1;
14430 ctx->argidx = -2;
14431 }
14432
14433 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014434 while (--ctx->fmtcnt >= 0) {
14435 arg->ch = FORMAT_READ(ctx);
14436 ctx->fmtpos++;
14437 switch (arg->ch) {
14438 case '-': arg->flags |= F_LJUST; continue;
14439 case '+': arg->flags |= F_SIGN; continue;
14440 case ' ': arg->flags |= F_BLANK; continue;
14441 case '#': arg->flags |= F_ALT; continue;
14442 case '0': arg->flags |= F_ZERO; continue;
14443 }
14444 break;
14445 }
14446
14447 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014448 if (arg->ch == '*') {
14449 v = unicode_format_getnextarg(ctx);
14450 if (v == NULL)
14451 return -1;
14452 if (!PyLong_Check(v)) {
14453 PyErr_SetString(PyExc_TypeError,
14454 "* wants int");
14455 return -1;
14456 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014457 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014458 if (arg->width == -1 && PyErr_Occurred())
14459 return -1;
14460 if (arg->width < 0) {
14461 arg->flags |= F_LJUST;
14462 arg->width = -arg->width;
14463 }
14464 if (--ctx->fmtcnt >= 0) {
14465 arg->ch = FORMAT_READ(ctx);
14466 ctx->fmtpos++;
14467 }
14468 }
14469 else if (arg->ch >= '0' && arg->ch <= '9') {
14470 arg->width = arg->ch - '0';
14471 while (--ctx->fmtcnt >= 0) {
14472 arg->ch = FORMAT_READ(ctx);
14473 ctx->fmtpos++;
14474 if (arg->ch < '0' || arg->ch > '9')
14475 break;
14476 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14477 mixing signed and unsigned comparison. Since arg->ch is between
14478 '0' and '9', casting to int is safe. */
14479 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14480 PyErr_SetString(PyExc_ValueError,
14481 "width too big");
14482 return -1;
14483 }
14484 arg->width = arg->width*10 + (arg->ch - '0');
14485 }
14486 }
14487
14488 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014489 if (arg->ch == '.') {
14490 arg->prec = 0;
14491 if (--ctx->fmtcnt >= 0) {
14492 arg->ch = FORMAT_READ(ctx);
14493 ctx->fmtpos++;
14494 }
14495 if (arg->ch == '*') {
14496 v = unicode_format_getnextarg(ctx);
14497 if (v == NULL)
14498 return -1;
14499 if (!PyLong_Check(v)) {
14500 PyErr_SetString(PyExc_TypeError,
14501 "* wants int");
14502 return -1;
14503 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014504 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014505 if (arg->prec == -1 && PyErr_Occurred())
14506 return -1;
14507 if (arg->prec < 0)
14508 arg->prec = 0;
14509 if (--ctx->fmtcnt >= 0) {
14510 arg->ch = FORMAT_READ(ctx);
14511 ctx->fmtpos++;
14512 }
14513 }
14514 else if (arg->ch >= '0' && arg->ch <= '9') {
14515 arg->prec = arg->ch - '0';
14516 while (--ctx->fmtcnt >= 0) {
14517 arg->ch = FORMAT_READ(ctx);
14518 ctx->fmtpos++;
14519 if (arg->ch < '0' || arg->ch > '9')
14520 break;
14521 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14522 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014523 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014524 return -1;
14525 }
14526 arg->prec = arg->prec*10 + (arg->ch - '0');
14527 }
14528 }
14529 }
14530
14531 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14532 if (ctx->fmtcnt >= 0) {
14533 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14534 if (--ctx->fmtcnt >= 0) {
14535 arg->ch = FORMAT_READ(ctx);
14536 ctx->fmtpos++;
14537 }
14538 }
14539 }
14540 if (ctx->fmtcnt < 0) {
14541 PyErr_SetString(PyExc_ValueError,
14542 "incomplete format");
14543 return -1;
14544 }
14545 return 0;
14546
14547#undef FORMAT_READ
14548}
14549
14550/* Format one argument. Supported conversion specifiers:
14551
14552 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014553 - "i", "d", "u": int or float
14554 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014555 - "e", "E", "f", "F", "g", "G": float
14556 - "c": int or str (1 character)
14557
Victor Stinner8dbd4212012-12-04 09:30:24 +010014558 When possible, the output is written directly into the Unicode writer
14559 (ctx->writer). A string is created when padding is required.
14560
Victor Stinnera47082312012-10-04 02:19:54 +020014561 Return 0 if the argument has been formatted into *p_str,
14562 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014563 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014564static int
14565unicode_format_arg_format(struct unicode_formatter_t *ctx,
14566 struct unicode_format_arg_t *arg,
14567 PyObject **p_str)
14568{
14569 PyObject *v;
14570 _PyUnicodeWriter *writer = &ctx->writer;
14571
14572 if (ctx->fmtcnt == 0)
14573 ctx->writer.overallocate = 0;
14574
Victor Stinnera47082312012-10-04 02:19:54 +020014575 v = unicode_format_getnextarg(ctx);
14576 if (v == NULL)
14577 return -1;
14578
Victor Stinnera47082312012-10-04 02:19:54 +020014579
14580 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014581 case 's':
14582 case 'r':
14583 case 'a':
14584 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14585 /* Fast path */
14586 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14587 return -1;
14588 return 1;
14589 }
14590
14591 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14592 *p_str = v;
14593 Py_INCREF(*p_str);
14594 }
14595 else {
14596 if (arg->ch == 's')
14597 *p_str = PyObject_Str(v);
14598 else if (arg->ch == 'r')
14599 *p_str = PyObject_Repr(v);
14600 else
14601 *p_str = PyObject_ASCII(v);
14602 }
14603 break;
14604
14605 case 'i':
14606 case 'd':
14607 case 'u':
14608 case 'o':
14609 case 'x':
14610 case 'X':
14611 {
14612 int ret = mainformatlong(v, arg, p_str, writer);
14613 if (ret != 0)
14614 return ret;
14615 arg->sign = 1;
14616 break;
14617 }
14618
14619 case 'e':
14620 case 'E':
14621 case 'f':
14622 case 'F':
14623 case 'g':
14624 case 'G':
14625 if (arg->width == -1 && arg->prec == -1
14626 && !(arg->flags & (F_SIGN | F_BLANK)))
14627 {
14628 /* Fast path */
14629 if (formatfloat(v, arg, NULL, writer) == -1)
14630 return -1;
14631 return 1;
14632 }
14633
14634 arg->sign = 1;
14635 if (formatfloat(v, arg, p_str, NULL) == -1)
14636 return -1;
14637 break;
14638
14639 case 'c':
14640 {
14641 Py_UCS4 ch = formatchar(v);
14642 if (ch == (Py_UCS4) -1)
14643 return -1;
14644 if (arg->width == -1 && arg->prec == -1) {
14645 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014646 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014647 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014648 return 1;
14649 }
14650 *p_str = PyUnicode_FromOrdinal(ch);
14651 break;
14652 }
14653
14654 default:
14655 PyErr_Format(PyExc_ValueError,
14656 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014657 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014658 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14659 (int)arg->ch,
14660 ctx->fmtpos - 1);
14661 return -1;
14662 }
14663 if (*p_str == NULL)
14664 return -1;
14665 assert (PyUnicode_Check(*p_str));
14666 return 0;
14667}
14668
14669static int
14670unicode_format_arg_output(struct unicode_formatter_t *ctx,
14671 struct unicode_format_arg_t *arg,
14672 PyObject *str)
14673{
14674 Py_ssize_t len;
14675 enum PyUnicode_Kind kind;
14676 void *pbuf;
14677 Py_ssize_t pindex;
14678 Py_UCS4 signchar;
14679 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014680 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014681 Py_ssize_t sublen;
14682 _PyUnicodeWriter *writer = &ctx->writer;
14683 Py_UCS4 fill;
14684
14685 fill = ' ';
14686 if (arg->sign && arg->flags & F_ZERO)
14687 fill = '0';
14688
14689 if (PyUnicode_READY(str) == -1)
14690 return -1;
14691
14692 len = PyUnicode_GET_LENGTH(str);
14693 if ((arg->width == -1 || arg->width <= len)
14694 && (arg->prec == -1 || arg->prec >= len)
14695 && !(arg->flags & (F_SIGN | F_BLANK)))
14696 {
14697 /* Fast path */
14698 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14699 return -1;
14700 return 0;
14701 }
14702
14703 /* Truncate the string for "s", "r" and "a" formats
14704 if the precision is set */
14705 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14706 if (arg->prec >= 0 && len > arg->prec)
14707 len = arg->prec;
14708 }
14709
14710 /* Adjust sign and width */
14711 kind = PyUnicode_KIND(str);
14712 pbuf = PyUnicode_DATA(str);
14713 pindex = 0;
14714 signchar = '\0';
14715 if (arg->sign) {
14716 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14717 if (ch == '-' || ch == '+') {
14718 signchar = ch;
14719 len--;
14720 pindex++;
14721 }
14722 else if (arg->flags & F_SIGN)
14723 signchar = '+';
14724 else if (arg->flags & F_BLANK)
14725 signchar = ' ';
14726 else
14727 arg->sign = 0;
14728 }
14729 if (arg->width < len)
14730 arg->width = len;
14731
14732 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014733 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014734 if (!(arg->flags & F_LJUST)) {
14735 if (arg->sign) {
14736 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014737 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014738 }
14739 else {
14740 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014741 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014742 }
14743 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014744 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14745 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014746 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014747 }
14748
Victor Stinnera47082312012-10-04 02:19:54 +020014749 buflen = arg->width;
14750 if (arg->sign && len == arg->width)
14751 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014752 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014753 return -1;
14754
14755 /* Write the sign if needed */
14756 if (arg->sign) {
14757 if (fill != ' ') {
14758 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14759 writer->pos += 1;
14760 }
14761 if (arg->width > len)
14762 arg->width--;
14763 }
14764
14765 /* Write the numeric prefix for "x", "X" and "o" formats
14766 if the alternate form is used.
14767 For example, write "0x" for the "%#x" format. */
14768 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14769 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14770 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14771 if (fill != ' ') {
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 arg->width -= 2;
14778 if (arg->width < 0)
14779 arg->width = 0;
14780 len -= 2;
14781 }
14782
14783 /* Pad left with the fill character if needed */
14784 if (arg->width > len && !(arg->flags & F_LJUST)) {
14785 sublen = arg->width - len;
14786 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14787 writer->pos += sublen;
14788 arg->width = len;
14789 }
14790
14791 /* If padding with spaces: write sign if needed and/or numeric prefix if
14792 the alternate form is used */
14793 if (fill == ' ') {
14794 if (arg->sign) {
14795 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14796 writer->pos += 1;
14797 }
14798 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14799 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14800 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14801 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14802 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14803 writer->pos += 2;
14804 pindex += 2;
14805 }
14806 }
14807
14808 /* Write characters */
14809 if (len) {
14810 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14811 str, pindex, len);
14812 writer->pos += len;
14813 }
14814
14815 /* Pad right with the fill character if needed */
14816 if (arg->width > len) {
14817 sublen = arg->width - len;
14818 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14819 writer->pos += sublen;
14820 }
14821 return 0;
14822}
14823
14824/* Helper of PyUnicode_Format(): format one arg.
14825 Return 0 on success, raise an exception and return -1 on error. */
14826static int
14827unicode_format_arg(struct unicode_formatter_t *ctx)
14828{
14829 struct unicode_format_arg_t arg;
14830 PyObject *str;
14831 int ret;
14832
Victor Stinner8dbd4212012-12-04 09:30:24 +010014833 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014834 if (arg.ch == '%') {
14835 ctx->fmtpos++;
14836 ctx->fmtcnt--;
14837 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14838 return -1;
14839 return 0;
14840 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014841 arg.flags = 0;
14842 arg.width = -1;
14843 arg.prec = -1;
14844 arg.sign = 0;
14845 str = NULL;
14846
Victor Stinnera47082312012-10-04 02:19:54 +020014847 ret = unicode_format_arg_parse(ctx, &arg);
14848 if (ret == -1)
14849 return -1;
14850
14851 ret = unicode_format_arg_format(ctx, &arg, &str);
14852 if (ret == -1)
14853 return -1;
14854
14855 if (ret != 1) {
14856 ret = unicode_format_arg_output(ctx, &arg, str);
14857 Py_DECREF(str);
14858 if (ret == -1)
14859 return -1;
14860 }
14861
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014862 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014863 PyErr_SetString(PyExc_TypeError,
14864 "not all arguments converted during string formatting");
14865 return -1;
14866 }
14867 return 0;
14868}
14869
Alexander Belopolsky40018472011-02-26 01:02:56 +000014870PyObject *
14871PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014872{
Victor Stinnera47082312012-10-04 02:19:54 +020014873 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014874
Guido van Rossumd57fd912000-03-10 22:53:23 +000014875 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014876 PyErr_BadInternalCall();
14877 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014878 }
Victor Stinnera47082312012-10-04 02:19:54 +020014879
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014880 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014881 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014882
14883 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014884 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14885 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14886 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14887 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014888
Victor Stinner8f674cc2013-04-17 23:02:17 +020014889 _PyUnicodeWriter_Init(&ctx.writer);
14890 ctx.writer.min_length = ctx.fmtcnt + 100;
14891 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014892
Guido van Rossumd57fd912000-03-10 22:53:23 +000014893 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014894 ctx.arglen = PyTuple_Size(args);
14895 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014896 }
14897 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014898 ctx.arglen = -1;
14899 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014900 }
Victor Stinnera47082312012-10-04 02:19:54 +020014901 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014902 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014903 ctx.dict = args;
14904 else
14905 ctx.dict = NULL;
14906 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014907
Victor Stinnera47082312012-10-04 02:19:54 +020014908 while (--ctx.fmtcnt >= 0) {
14909 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014910 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014911
14912 nonfmtpos = ctx.fmtpos++;
14913 while (ctx.fmtcnt >= 0 &&
14914 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14915 ctx.fmtpos++;
14916 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014917 }
Victor Stinnera47082312012-10-04 02:19:54 +020014918 if (ctx.fmtcnt < 0) {
14919 ctx.fmtpos--;
14920 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014921 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014922
Victor Stinnercfc4c132013-04-03 01:48:39 +020014923 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14924 nonfmtpos, ctx.fmtpos) < 0)
14925 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014926 }
14927 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014928 ctx.fmtpos++;
14929 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014930 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014931 }
14932 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014933
Victor Stinnera47082312012-10-04 02:19:54 +020014934 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014935 PyErr_SetString(PyExc_TypeError,
14936 "not all arguments converted during string formatting");
14937 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014938 }
14939
Victor Stinnera47082312012-10-04 02:19:54 +020014940 if (ctx.args_owned) {
14941 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014942 }
Victor Stinnera47082312012-10-04 02:19:54 +020014943 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014944
Benjamin Peterson29060642009-01-31 22:14:21 +000014945 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014946 _PyUnicodeWriter_Dealloc(&ctx.writer);
14947 if (ctx.args_owned) {
14948 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014949 }
14950 return NULL;
14951}
14952
Jeremy Hylton938ace62002-07-17 16:30:39 +000014953static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014954unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14955
Tim Peters6d6c1a32001-08-02 04:15:00 +000014956static PyObject *
14957unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14958{
Benjamin Peterson29060642009-01-31 22:14:21 +000014959 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014960 static char *kwlist[] = {"object", "encoding", "errors", 0};
14961 char *encoding = NULL;
14962 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014963
Benjamin Peterson14339b62009-01-31 16:36:08 +000014964 if (type != &PyUnicode_Type)
14965 return unicode_subtype_new(type, args, kwds);
14966 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014967 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014968 return NULL;
14969 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014970 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014971 if (encoding == NULL && errors == NULL)
14972 return PyObject_Str(x);
14973 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014974 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014975}
14976
Guido van Rossume023fe02001-08-30 03:12:59 +000014977static PyObject *
14978unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14979{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014980 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014981 Py_ssize_t length, char_size;
14982 int share_wstr, share_utf8;
14983 unsigned int kind;
14984 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014985
Benjamin Peterson14339b62009-01-31 16:36:08 +000014986 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014987
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014988 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014989 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014990 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014991 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014992 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014993 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014994 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014995 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014996
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014997 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014998 if (self == NULL) {
14999 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015000 return NULL;
15001 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015002 kind = PyUnicode_KIND(unicode);
15003 length = PyUnicode_GET_LENGTH(unicode);
15004
15005 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015006#ifdef Py_DEBUG
15007 _PyUnicode_HASH(self) = -1;
15008#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015009 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015010#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015011 _PyUnicode_STATE(self).interned = 0;
15012 _PyUnicode_STATE(self).kind = kind;
15013 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015014 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015015 _PyUnicode_STATE(self).ready = 1;
15016 _PyUnicode_WSTR(self) = NULL;
15017 _PyUnicode_UTF8_LENGTH(self) = 0;
15018 _PyUnicode_UTF8(self) = NULL;
15019 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015020 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015021
15022 share_utf8 = 0;
15023 share_wstr = 0;
15024 if (kind == PyUnicode_1BYTE_KIND) {
15025 char_size = 1;
15026 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15027 share_utf8 = 1;
15028 }
15029 else if (kind == PyUnicode_2BYTE_KIND) {
15030 char_size = 2;
15031 if (sizeof(wchar_t) == 2)
15032 share_wstr = 1;
15033 }
15034 else {
15035 assert(kind == PyUnicode_4BYTE_KIND);
15036 char_size = 4;
15037 if (sizeof(wchar_t) == 4)
15038 share_wstr = 1;
15039 }
15040
15041 /* Ensure we won't overflow the length. */
15042 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15043 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015044 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015045 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015046 data = PyObject_MALLOC((length + 1) * char_size);
15047 if (data == NULL) {
15048 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015049 goto onError;
15050 }
15051
Victor Stinnerc3c74152011-10-02 20:39:55 +020015052 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015053 if (share_utf8) {
15054 _PyUnicode_UTF8_LENGTH(self) = length;
15055 _PyUnicode_UTF8(self) = data;
15056 }
15057 if (share_wstr) {
15058 _PyUnicode_WSTR_LENGTH(self) = length;
15059 _PyUnicode_WSTR(self) = (wchar_t *)data;
15060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015061
Christian Heimesf051e432016-09-13 20:22:02 +020015062 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015063 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015064 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015065#ifdef Py_DEBUG
15066 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15067#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015068 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015069 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015070
15071onError:
15072 Py_DECREF(unicode);
15073 Py_DECREF(self);
15074 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015075}
15076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015077PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015078"str(object='') -> str\n\
15079str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015080\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015081Create a new string object from the given object. If encoding or\n\
15082errors is specified, then the object must expose a data buffer\n\
15083that will be decoded using the given encoding and error handler.\n\
15084Otherwise, returns the result of object.__str__() (if defined)\n\
15085or repr(object).\n\
15086encoding defaults to sys.getdefaultencoding().\n\
15087errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015088
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015089static PyObject *unicode_iter(PyObject *seq);
15090
Guido van Rossumd57fd912000-03-10 22:53:23 +000015091PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015092 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015093 "str", /* tp_name */
15094 sizeof(PyUnicodeObject), /* tp_basicsize */
15095 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015096 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015097 (destructor)unicode_dealloc, /* tp_dealloc */
15098 0, /* tp_print */
15099 0, /* tp_getattr */
15100 0, /* tp_setattr */
15101 0, /* tp_reserved */
15102 unicode_repr, /* tp_repr */
15103 &unicode_as_number, /* tp_as_number */
15104 &unicode_as_sequence, /* tp_as_sequence */
15105 &unicode_as_mapping, /* tp_as_mapping */
15106 (hashfunc) unicode_hash, /* tp_hash*/
15107 0, /* tp_call*/
15108 (reprfunc) unicode_str, /* tp_str */
15109 PyObject_GenericGetAttr, /* tp_getattro */
15110 0, /* tp_setattro */
15111 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015113 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15114 unicode_doc, /* tp_doc */
15115 0, /* tp_traverse */
15116 0, /* tp_clear */
15117 PyUnicode_RichCompare, /* tp_richcompare */
15118 0, /* tp_weaklistoffset */
15119 unicode_iter, /* tp_iter */
15120 0, /* tp_iternext */
15121 unicode_methods, /* tp_methods */
15122 0, /* tp_members */
15123 0, /* tp_getset */
15124 &PyBaseObject_Type, /* tp_base */
15125 0, /* tp_dict */
15126 0, /* tp_descr_get */
15127 0, /* tp_descr_set */
15128 0, /* tp_dictoffset */
15129 0, /* tp_init */
15130 0, /* tp_alloc */
15131 unicode_new, /* tp_new */
15132 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015133};
15134
15135/* Initialize the Unicode implementation */
15136
Victor Stinner3a50e702011-10-18 21:21:00 +020015137int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015138{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015139 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015140 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015141 0x000A, /* LINE FEED */
15142 0x000D, /* CARRIAGE RETURN */
15143 0x001C, /* FILE SEPARATOR */
15144 0x001D, /* GROUP SEPARATOR */
15145 0x001E, /* RECORD SEPARATOR */
15146 0x0085, /* NEXT LINE */
15147 0x2028, /* LINE SEPARATOR */
15148 0x2029, /* PARAGRAPH SEPARATOR */
15149 };
15150
Fred Drakee4315f52000-05-09 19:53:39 +000015151 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015152 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015153 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015154 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015155 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015156
Guido van Rossumcacfc072002-05-24 19:01:59 +000015157 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015158 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015159
15160 /* initialize the linebreak bloom filter */
15161 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015162 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015163 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015164
Christian Heimes26532f72013-07-20 14:57:16 +020015165 if (PyType_Ready(&EncodingMapType) < 0)
15166 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015167
Benjamin Petersonc4311282012-10-30 23:21:10 -040015168 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15169 Py_FatalError("Can't initialize field name iterator type");
15170
15171 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15172 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015173
Victor Stinner3a50e702011-10-18 21:21:00 +020015174 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015175}
15176
15177/* Finalize the Unicode implementation */
15178
Christian Heimesa156e092008-02-16 07:38:31 +000015179int
15180PyUnicode_ClearFreeList(void)
15181{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015182 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015183}
15184
Guido van Rossumd57fd912000-03-10 22:53:23 +000015185void
Thomas Wouters78890102000-07-22 19:25:51 +000015186_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015187{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015188 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015189
Serhiy Storchaka05997252013-01-26 12:14:02 +020015190 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015191
Serhiy Storchaka05997252013-01-26 12:14:02 +020015192 for (i = 0; i < 256; i++)
15193 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015194 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015195 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015196}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015197
Walter Dörwald16807132007-05-25 13:52:07 +000015198void
15199PyUnicode_InternInPlace(PyObject **p)
15200{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015201 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015203#ifdef Py_DEBUG
15204 assert(s != NULL);
15205 assert(_PyUnicode_CHECK(s));
15206#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015208 return;
15209#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015210 /* If it's a subclass, we don't really know what putting
15211 it in the interned dict might do. */
15212 if (!PyUnicode_CheckExact(s))
15213 return;
15214 if (PyUnicode_CHECK_INTERNED(s))
15215 return;
15216 if (interned == NULL) {
15217 interned = PyDict_New();
15218 if (interned == NULL) {
15219 PyErr_Clear(); /* Don't leave an exception */
15220 return;
15221 }
15222 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015223 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015224 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015225 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015226 if (t == NULL) {
15227 PyErr_Clear();
15228 return;
15229 }
15230 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015231 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015232 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015233 return;
15234 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015235 /* The two references in interned are not counted by refcnt.
15236 The deallocator will take care of this */
15237 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015238 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015239}
15240
15241void
15242PyUnicode_InternImmortal(PyObject **p)
15243{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015244 PyUnicode_InternInPlace(p);
15245 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015246 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015247 Py_INCREF(*p);
15248 }
Walter Dörwald16807132007-05-25 13:52:07 +000015249}
15250
15251PyObject *
15252PyUnicode_InternFromString(const char *cp)
15253{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015254 PyObject *s = PyUnicode_FromString(cp);
15255 if (s == NULL)
15256 return NULL;
15257 PyUnicode_InternInPlace(&s);
15258 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015259}
15260
Alexander Belopolsky40018472011-02-26 01:02:56 +000015261void
15262_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015263{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015264 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015265 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015266 Py_ssize_t i, n;
15267 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015268
Benjamin Peterson14339b62009-01-31 16:36:08 +000015269 if (interned == NULL || !PyDict_Check(interned))
15270 return;
15271 keys = PyDict_Keys(interned);
15272 if (keys == NULL || !PyList_Check(keys)) {
15273 PyErr_Clear();
15274 return;
15275 }
Walter Dörwald16807132007-05-25 13:52:07 +000015276
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15278 detector, interned unicode strings are not forcibly deallocated;
15279 rather, we give them their stolen references back, and then clear
15280 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015281
Benjamin Peterson14339b62009-01-31 16:36:08 +000015282 n = PyList_GET_SIZE(keys);
15283 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015284 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015285 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015286 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015287 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015288 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015289 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015290 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 case SSTATE_NOT_INTERNED:
15292 /* XXX Shouldn't happen */
15293 break;
15294 case SSTATE_INTERNED_IMMORTAL:
15295 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015296 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 break;
15298 case SSTATE_INTERNED_MORTAL:
15299 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015300 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 break;
15302 default:
15303 Py_FatalError("Inconsistent interned string state.");
15304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015305 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 }
15307 fprintf(stderr, "total size of all interned strings: "
15308 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15309 "mortal/immortal\n", mortal_size, immortal_size);
15310 Py_DECREF(keys);
15311 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015312 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015313}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015314
15315
15316/********************* Unicode Iterator **************************/
15317
15318typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015319 PyObject_HEAD
15320 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015321 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015322} unicodeiterobject;
15323
15324static void
15325unicodeiter_dealloc(unicodeiterobject *it)
15326{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015327 _PyObject_GC_UNTRACK(it);
15328 Py_XDECREF(it->it_seq);
15329 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015330}
15331
15332static int
15333unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15334{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015335 Py_VISIT(it->it_seq);
15336 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015337}
15338
15339static PyObject *
15340unicodeiter_next(unicodeiterobject *it)
15341{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015342 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015343
Benjamin Peterson14339b62009-01-31 16:36:08 +000015344 assert(it != NULL);
15345 seq = it->it_seq;
15346 if (seq == NULL)
15347 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015348 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015350 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15351 int kind = PyUnicode_KIND(seq);
15352 void *data = PyUnicode_DATA(seq);
15353 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15354 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015355 if (item != NULL)
15356 ++it->it_index;
15357 return item;
15358 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015359
Benjamin Peterson14339b62009-01-31 16:36:08 +000015360 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015361 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015362 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015363}
15364
15365static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015366unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015367{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015368 Py_ssize_t len = 0;
15369 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015370 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015371 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015372}
15373
15374PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15375
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015376static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015377unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015378{
15379 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015380 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015381 it->it_seq, it->it_index);
15382 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015383 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015384 if (u == NULL)
15385 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015386 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015387 }
15388}
15389
15390PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15391
15392static PyObject *
15393unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15394{
15395 Py_ssize_t index = PyLong_AsSsize_t(state);
15396 if (index == -1 && PyErr_Occurred())
15397 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015398 if (it->it_seq != NULL) {
15399 if (index < 0)
15400 index = 0;
15401 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15402 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15403 it->it_index = index;
15404 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015405 Py_RETURN_NONE;
15406}
15407
15408PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15409
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015410static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015412 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015413 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15414 reduce_doc},
15415 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15416 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015417 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015418};
15419
15420PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015421 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15422 "str_iterator", /* tp_name */
15423 sizeof(unicodeiterobject), /* tp_basicsize */
15424 0, /* tp_itemsize */
15425 /* methods */
15426 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15427 0, /* tp_print */
15428 0, /* tp_getattr */
15429 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015430 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015431 0, /* tp_repr */
15432 0, /* tp_as_number */
15433 0, /* tp_as_sequence */
15434 0, /* tp_as_mapping */
15435 0, /* tp_hash */
15436 0, /* tp_call */
15437 0, /* tp_str */
15438 PyObject_GenericGetAttr, /* tp_getattro */
15439 0, /* tp_setattro */
15440 0, /* tp_as_buffer */
15441 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15442 0, /* tp_doc */
15443 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15444 0, /* tp_clear */
15445 0, /* tp_richcompare */
15446 0, /* tp_weaklistoffset */
15447 PyObject_SelfIter, /* tp_iter */
15448 (iternextfunc)unicodeiter_next, /* tp_iternext */
15449 unicodeiter_methods, /* tp_methods */
15450 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015451};
15452
15453static PyObject *
15454unicode_iter(PyObject *seq)
15455{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015456 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015457
Benjamin Peterson14339b62009-01-31 16:36:08 +000015458 if (!PyUnicode_Check(seq)) {
15459 PyErr_BadInternalCall();
15460 return NULL;
15461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015462 if (PyUnicode_READY(seq) == -1)
15463 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015464 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15465 if (it == NULL)
15466 return NULL;
15467 it->it_index = 0;
15468 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015469 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015470 _PyObject_GC_TRACK(it);
15471 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015472}
15473
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015474
15475size_t
15476Py_UNICODE_strlen(const Py_UNICODE *u)
15477{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015478 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015479}
15480
15481Py_UNICODE*
15482Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15483{
15484 Py_UNICODE *u = s1;
15485 while ((*u++ = *s2++));
15486 return s1;
15487}
15488
15489Py_UNICODE*
15490Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15491{
15492 Py_UNICODE *u = s1;
15493 while ((*u++ = *s2++))
15494 if (n-- == 0)
15495 break;
15496 return s1;
15497}
15498
15499Py_UNICODE*
15500Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15501{
15502 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015503 u1 += wcslen(u1);
15504 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015505 return s1;
15506}
15507
15508int
15509Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15510{
15511 while (*s1 && *s2 && *s1 == *s2)
15512 s1++, s2++;
15513 if (*s1 && *s2)
15514 return (*s1 < *s2) ? -1 : +1;
15515 if (*s1)
15516 return 1;
15517 if (*s2)
15518 return -1;
15519 return 0;
15520}
15521
15522int
15523Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15524{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015525 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015526 for (; n != 0; n--) {
15527 u1 = *s1;
15528 u2 = *s2;
15529 if (u1 != u2)
15530 return (u1 < u2) ? -1 : +1;
15531 if (u1 == '\0')
15532 return 0;
15533 s1++;
15534 s2++;
15535 }
15536 return 0;
15537}
15538
15539Py_UNICODE*
15540Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15541{
15542 const Py_UNICODE *p;
15543 for (p = s; *p; p++)
15544 if (*p == c)
15545 return (Py_UNICODE*)p;
15546 return NULL;
15547}
15548
15549Py_UNICODE*
15550Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15551{
15552 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015553 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015554 while (p != s) {
15555 p--;
15556 if (*p == c)
15557 return (Py_UNICODE*)p;
15558 }
15559 return NULL;
15560}
Victor Stinner331ea922010-08-10 16:37:20 +000015561
Victor Stinner71133ff2010-09-01 23:43:53 +000015562Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015563PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015564{
Victor Stinner577db2c2011-10-11 22:12:48 +020015565 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015566 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015568 if (!PyUnicode_Check(unicode)) {
15569 PyErr_BadArgument();
15570 return NULL;
15571 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015572 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015573 if (u == NULL)
15574 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015575 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015576 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015577 PyErr_NoMemory();
15578 return NULL;
15579 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015580 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015581 size *= sizeof(Py_UNICODE);
15582 copy = PyMem_Malloc(size);
15583 if (copy == NULL) {
15584 PyErr_NoMemory();
15585 return NULL;
15586 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015587 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015588 return copy;
15589}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015590
Georg Brandl66c221e2010-10-14 07:04:07 +000015591/* A _string module, to export formatter_parser and formatter_field_name_split
15592 to the string.Formatter class implemented in Python. */
15593
15594static PyMethodDef _string_methods[] = {
15595 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15596 METH_O, PyDoc_STR("split the argument as a field name")},
15597 {"formatter_parser", (PyCFunction) formatter_parser,
15598 METH_O, PyDoc_STR("parse the argument as a format string")},
15599 {NULL, NULL}
15600};
15601
15602static struct PyModuleDef _string_module = {
15603 PyModuleDef_HEAD_INIT,
15604 "_string",
15605 PyDoc_STR("string helper module"),
15606 0,
15607 _string_methods,
15608 NULL,
15609 NULL,
15610 NULL,
15611 NULL
15612};
15613
15614PyMODINIT_FUNC
15615PyInit__string(void)
15616{
15617 return PyModule_Create(&_string_module);
15618}
15619
15620
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015621#ifdef __cplusplus
15622}
15623#endif