blob: 716e352dea611dfca33f74da497e64e611248991 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043#include "internal/pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050045#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070046#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000047
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000048#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000049#include <windows.h>
50#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000051
Larry Hastings61272b72014-01-07 12:41:53 -080052/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090053class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080054[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090055/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
56
57/*[python input]
58class Py_UCS4_converter(CConverter):
59 type = 'Py_UCS4'
60 converter = 'convert_uc'
61
62 def converter_init(self):
63 if self.default is not unspecified:
64 self.c_default = ascii(self.default)
65 if len(self.c_default) > 4 or self.c_default[0] != "'":
66 self.c_default = hex(ord(self.default))
67
68[python start generated code]*/
69/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080070
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000071/* --- Globals ------------------------------------------------------------
72
Serhiy Storchaka05997252013-01-26 12:14:02 +020073NOTE: In the interpreter's initialization phase, some globals are currently
74 initialized dynamically as needed. In the process Unicode objects may
75 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000076
77*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000078
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079
80#ifdef __cplusplus
81extern "C" {
82#endif
83
Victor Stinner8faf8212011-12-08 22:14:11 +010084/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
85#define MAX_UNICODE 0x10ffff
86
Victor Stinner910337b2011-10-03 03:20:16 +020087#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020088# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020089#else
90# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
91#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020092
Victor Stinnere90fe6a2011-10-01 16:48:13 +020093#define _PyUnicode_UTF8(op) \
94 (((PyCompactUnicodeObject*)(op))->utf8)
95#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020096 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020097 assert(PyUnicode_IS_READY(op)), \
98 PyUnicode_IS_COMPACT_ASCII(op) ? \
99 ((char*)((PyASCIIObject*)(op) + 1)) : \
100 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200101#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 (((PyCompactUnicodeObject*)(op))->utf8_length)
103#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200104 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200105 assert(PyUnicode_IS_READY(op)), \
106 PyUnicode_IS_COMPACT_ASCII(op) ? \
107 ((PyASCIIObject*)(op))->length : \
108 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_WSTR(op) \
110 (((PyASCIIObject*)(op))->wstr)
111#define _PyUnicode_WSTR_LENGTH(op) \
112 (((PyCompactUnicodeObject*)(op))->wstr_length)
113#define _PyUnicode_LENGTH(op) \
114 (((PyASCIIObject *)(op))->length)
115#define _PyUnicode_STATE(op) \
116 (((PyASCIIObject *)(op))->state)
117#define _PyUnicode_HASH(op) \
118 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200125#define _PyUnicode_DATA_ANY(op) \
126 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200127
Victor Stinner910337b2011-10-03 03:20:16 +0200128#undef PyUnicode_READY
129#define PyUnicode_READY(op) \
130 (assert(_PyUnicode_CHECK(op)), \
131 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200132 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100133 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200134
Victor Stinnerc379ead2011-10-03 12:52:27 +0200135#define _PyUnicode_SHARE_UTF8(op) \
136 (assert(_PyUnicode_CHECK(op)), \
137 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
138 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
139#define _PyUnicode_SHARE_WSTR(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
142
Victor Stinner829c0ad2011-10-03 01:08:02 +0200143/* true if the Unicode object has an allocated UTF-8 memory block
144 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200145#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200146 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200147 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200148 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
149
Victor Stinner03490912011-10-03 23:45:12 +0200150/* true if the Unicode object has an allocated wstr memory block
151 (not shared with other data) */
152#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200153 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200154 (!PyUnicode_IS_READY(op) || \
155 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
156
Victor Stinner910337b2011-10-03 03:20:16 +0200157/* Generic helper macro to convert characters of different types.
158 from_type and to_type have to be valid type names, begin and end
159 are pointers to the source characters which should be of type
160 "from_type *". to is a pointer of type "to_type *" and points to the
161 buffer where the result characters are written to. */
162#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
163 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100164 to_type *_to = (to_type *)(to); \
165 const from_type *_iter = (from_type *)(begin); \
166 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200167 Py_ssize_t n = (_end) - (_iter); \
168 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200169 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_unrolled_end)) { \
171 _to[0] = (to_type) _iter[0]; \
172 _to[1] = (to_type) _iter[1]; \
173 _to[2] = (to_type) _iter[2]; \
174 _to[3] = (to_type) _iter[3]; \
175 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200176 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200177 while (_iter < (_end)) \
178 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200179 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200180
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200181#ifdef MS_WINDOWS
182 /* On Windows, overallocate by 50% is the best factor */
183# define OVERALLOCATE_FACTOR 2
184#else
185 /* On Linux, overallocate by 25% is the best factor */
186# define OVERALLOCATE_FACTOR 4
187#endif
188
Walter Dörwald16807132007-05-25 13:52:07 +0000189/* This dictionary holds all interned unicode strings. Note that references
190 to strings in this dictionary are *not* counted in the string's ob_refcnt.
191 When the interned string reaches a refcnt of 0 the string deallocation
192 function will delete the reference from this dictionary.
193
194 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000195 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000196*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000198
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200201
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200203 do { \
204 if (unicode_empty != NULL) \
205 Py_INCREF(unicode_empty); \
206 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207 unicode_empty = PyUnicode_New(0, 0); \
208 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200209 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200210 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
211 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200213 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000214
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215#define _Py_RETURN_UNICODE_EMPTY() \
216 do { \
217 _Py_INCREF_UNICODE_EMPTY(); \
218 return unicode_empty; \
219 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000220
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200221/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700222static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200223_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
224
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200225/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200226static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200227
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000228/* Single character Unicode strings in the Latin-1 range are being
229 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200230static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000231
Christian Heimes190d79e2008-01-30 11:58:22 +0000232/* Fast detection of the most frequent whitespace characters */
233const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000235/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000236/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000237/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000238/* case 0x000C: * FORM FEED */
239/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000240 0, 1, 1, 1, 1, 1, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000242/* case 0x001C: * FILE SEPARATOR */
243/* case 0x001D: * GROUP SEPARATOR */
244/* case 0x001E: * RECORD SEPARATOR */
245/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000246 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000247/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000248 1, 0, 0, 0, 0, 0, 0, 0,
249 0, 0, 0, 0, 0, 0, 0, 0,
250 0, 0, 0, 0, 0, 0, 0, 0,
251 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000252
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
254 0, 0, 0, 0, 0, 0, 0, 0,
255 0, 0, 0, 0, 0, 0, 0, 0,
256 0, 0, 0, 0, 0, 0, 0, 0,
257 0, 0, 0, 0, 0, 0, 0, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000261};
262
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200263/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200264static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200265static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100266static int unicode_modifiable(PyObject *unicode);
267
Victor Stinnerfe226c02011-10-03 03:52:20 +0200268
Alexander Belopolsky40018472011-02-26 01:02:56 +0000269static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100270_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200271static PyObject *
272_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
273static PyObject *
274_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
275
276static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000277unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000278 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100279 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000280 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
281
Alexander Belopolsky40018472011-02-26 01:02:56 +0000282static void
283raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300284 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100285 PyObject *unicode,
286 Py_ssize_t startpos, Py_ssize_t endpos,
287 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000288
Christian Heimes190d79e2008-01-30 11:58:22 +0000289/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200290static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000292/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000293/* 0x000B, * LINE TABULATION */
294/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000295/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000296 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000298/* 0x001C, * FILE SEPARATOR */
299/* 0x001D, * GROUP SEPARATOR */
300/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 0, 0, 0, 0, 1, 1, 1, 0,
302 0, 0, 0, 0, 0, 0, 0, 0,
303 0, 0, 0, 0, 0, 0, 0, 0,
304 0, 0, 0, 0, 0, 0, 0, 0,
305 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000306
Benjamin Peterson14339b62009-01-31 16:36:08 +0000307 0, 0, 0, 0, 0, 0, 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0,
309 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0, 0, 0, 0, 0,
311 0, 0, 0, 0, 0, 0, 0, 0,
312 0, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0,
314 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000315};
316
INADA Naoki3ae20562017-01-16 20:41:20 +0900317static int convert_uc(PyObject *obj, void *addr);
318
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300319#include "clinic/unicodeobject.c.h"
320
Victor Stinner50149202015-09-22 00:26:54 +0200321typedef enum {
322 _Py_ERROR_UNKNOWN=0,
323 _Py_ERROR_STRICT,
324 _Py_ERROR_SURROGATEESCAPE,
325 _Py_ERROR_REPLACE,
326 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200327 _Py_ERROR_BACKSLASHREPLACE,
328 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200329 _Py_ERROR_XMLCHARREFREPLACE,
330 _Py_ERROR_OTHER
331} _Py_error_handler;
332
333static _Py_error_handler
334get_error_handler(const char *errors)
335{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200337 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200338 }
339 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200341 }
342 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200343 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200344 }
345 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200346 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200347 }
348 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200349 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200350 }
351 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200352 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200353 }
354 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200355 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200356 }
Victor Stinner50149202015-09-22 00:26:54 +0200357 return _Py_ERROR_OTHER;
358}
359
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300360/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
361 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000362Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000363PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000364{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000365#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000366 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000367#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000368 /* This is actually an illegal character, so it should
369 not be passed to unichr. */
370 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000371#endif
372}
373
Victor Stinner910337b2011-10-03 03:20:16 +0200374#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200375int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100376_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200377{
378 PyASCIIObject *ascii;
379 unsigned int kind;
380
381 assert(PyUnicode_Check(op));
382
383 ascii = (PyASCIIObject *)op;
384 kind = ascii->state.kind;
385
Victor Stinnera3b334d2011-10-03 13:53:37 +0200386 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200387 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 assert(ascii->state.ready == 1);
389 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200391 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200392 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200393
Victor Stinnera41463c2011-10-04 01:05:08 +0200394 if (ascii->state.compact == 1) {
395 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200396 assert(kind == PyUnicode_1BYTE_KIND
397 || kind == PyUnicode_2BYTE_KIND
398 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200399 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200400 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200401 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100402 }
403 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200404 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
405
406 data = unicode->data.any;
407 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100408 assert(ascii->length == 0);
409 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200410 assert(ascii->state.compact == 0);
411 assert(ascii->state.ascii == 0);
412 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100413 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200414 assert(ascii->wstr != NULL);
415 assert(data == NULL);
416 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 }
418 else {
419 assert(kind == PyUnicode_1BYTE_KIND
420 || kind == PyUnicode_2BYTE_KIND
421 || kind == PyUnicode_4BYTE_KIND);
422 assert(ascii->state.compact == 0);
423 assert(ascii->state.ready == 1);
424 assert(data != NULL);
425 if (ascii->state.ascii) {
426 assert (compact->utf8 == data);
427 assert (compact->utf8_length == ascii->length);
428 }
429 else
430 assert (compact->utf8 != data);
431 }
432 }
433 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200434 if (
435#if SIZEOF_WCHAR_T == 2
436 kind == PyUnicode_2BYTE_KIND
437#else
438 kind == PyUnicode_4BYTE_KIND
439#endif
440 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200441 {
442 assert(ascii->wstr == data);
443 assert(compact->wstr_length == ascii->length);
444 } else
445 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200446 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200447
448 if (compact->utf8 == NULL)
449 assert(compact->utf8_length == 0);
450 if (ascii->wstr == NULL)
451 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200452 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 /* check that the best kind is used */
454 if (check_content && kind != PyUnicode_WCHAR_KIND)
455 {
456 Py_ssize_t i;
457 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200458 void *data;
459 Py_UCS4 ch;
460
461 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200462 for (i=0; i < ascii->length; i++)
463 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200464 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200465 if (ch > maxchar)
466 maxchar = ch;
467 }
468 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100469 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200470 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100471 assert(maxchar <= 255);
472 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200473 else
474 assert(maxchar < 128);
475 }
Victor Stinner77faf692011-11-20 18:56:05 +0100476 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200477 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100478 assert(maxchar <= 0xFFFF);
479 }
480 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200481 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100482 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100483 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200484 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200485 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400486 return 1;
487}
Victor Stinner910337b2011-10-03 03:20:16 +0200488#endif
489
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100490static PyObject*
491unicode_result_wchar(PyObject *unicode)
492{
493#ifndef Py_DEBUG
494 Py_ssize_t len;
495
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 len = _PyUnicode_WSTR_LENGTH(unicode);
497 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100498 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200499 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100500 }
501
502 if (len == 1) {
503 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100504 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100505 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
506 Py_DECREF(unicode);
507 return latin1_char;
508 }
509 }
510
511 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200512 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100513 return NULL;
514 }
515#else
Victor Stinneraa771272012-10-04 02:32:58 +0200516 assert(Py_REFCNT(unicode) == 1);
517
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 /* don't make the result ready in debug mode to ensure that the caller
519 makes the string ready before using it */
520 assert(_PyUnicode_CheckConsistency(unicode, 1));
521#endif
522 return unicode;
523}
524
525static PyObject*
526unicode_result_ready(PyObject *unicode)
527{
528 Py_ssize_t length;
529
530 length = PyUnicode_GET_LENGTH(unicode);
531 if (length == 0) {
532 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100533 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200534 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100535 }
536 return unicode_empty;
537 }
538
539 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200540 void *data = PyUnicode_DATA(unicode);
541 int kind = PyUnicode_KIND(unicode);
542 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100543 if (ch < 256) {
544 PyObject *latin1_char = unicode_latin1[ch];
545 if (latin1_char != NULL) {
546 if (unicode != latin1_char) {
547 Py_INCREF(latin1_char);
548 Py_DECREF(unicode);
549 }
550 return latin1_char;
551 }
552 else {
553 assert(_PyUnicode_CheckConsistency(unicode, 1));
554 Py_INCREF(unicode);
555 unicode_latin1[ch] = unicode;
556 return unicode;
557 }
558 }
559 }
560
561 assert(_PyUnicode_CheckConsistency(unicode, 1));
562 return unicode;
563}
564
565static PyObject*
566unicode_result(PyObject *unicode)
567{
568 assert(_PyUnicode_CHECK(unicode));
569 if (PyUnicode_IS_READY(unicode))
570 return unicode_result_ready(unicode);
571 else
572 return unicode_result_wchar(unicode);
573}
574
Victor Stinnerc4b49542011-12-11 22:44:26 +0100575static PyObject*
576unicode_result_unchanged(PyObject *unicode)
577{
578 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500579 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100580 return NULL;
581 Py_INCREF(unicode);
582 return unicode;
583 }
584 else
585 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100586 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100587}
588
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200589/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
590 ASCII, Latin1, UTF-8, etc. */
591static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200592backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
594{
Victor Stinnerad771582015-10-09 12:38:53 +0200595 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200596 Py_UCS4 ch;
597 enum PyUnicode_Kind kind;
598 void *data;
599
600 assert(PyUnicode_IS_READY(unicode));
601 kind = PyUnicode_KIND(unicode);
602 data = PyUnicode_DATA(unicode);
603
604 size = 0;
605 /* determine replacement size */
606 for (i = collstart; i < collend; ++i) {
607 Py_ssize_t incr;
608
609 ch = PyUnicode_READ(kind, data, i);
610 if (ch < 0x100)
611 incr = 2+2;
612 else if (ch < 0x10000)
613 incr = 2+4;
614 else {
615 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200616 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200617 }
618 if (size > PY_SSIZE_T_MAX - incr) {
619 PyErr_SetString(PyExc_OverflowError,
620 "encoded result is too long for a Python string");
621 return NULL;
622 }
623 size += incr;
624 }
625
Victor Stinnerad771582015-10-09 12:38:53 +0200626 str = _PyBytesWriter_Prepare(writer, str, size);
627 if (str == NULL)
628 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200629
630 /* generate replacement */
631 for (i = collstart; i < collend; ++i) {
632 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200633 *str++ = '\\';
634 if (ch >= 0x00010000) {
635 *str++ = 'U';
636 *str++ = Py_hexdigits[(ch>>28)&0xf];
637 *str++ = Py_hexdigits[(ch>>24)&0xf];
638 *str++ = Py_hexdigits[(ch>>20)&0xf];
639 *str++ = Py_hexdigits[(ch>>16)&0xf];
640 *str++ = Py_hexdigits[(ch>>12)&0xf];
641 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200642 }
Victor Stinner797485e2015-10-09 03:17:30 +0200643 else if (ch >= 0x100) {
644 *str++ = 'u';
645 *str++ = Py_hexdigits[(ch>>12)&0xf];
646 *str++ = Py_hexdigits[(ch>>8)&0xf];
647 }
648 else
649 *str++ = 'x';
650 *str++ = Py_hexdigits[(ch>>4)&0xf];
651 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200652 }
653 return str;
654}
655
656/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
657 ASCII, Latin1, UTF-8, etc. */
658static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200659xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200660 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
661{
Victor Stinnerad771582015-10-09 12:38:53 +0200662 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200663 Py_UCS4 ch;
664 enum PyUnicode_Kind kind;
665 void *data;
666
667 assert(PyUnicode_IS_READY(unicode));
668 kind = PyUnicode_KIND(unicode);
669 data = PyUnicode_DATA(unicode);
670
671 size = 0;
672 /* determine replacement size */
673 for (i = collstart; i < collend; ++i) {
674 Py_ssize_t incr;
675
676 ch = PyUnicode_READ(kind, data, i);
677 if (ch < 10)
678 incr = 2+1+1;
679 else if (ch < 100)
680 incr = 2+2+1;
681 else if (ch < 1000)
682 incr = 2+3+1;
683 else if (ch < 10000)
684 incr = 2+4+1;
685 else if (ch < 100000)
686 incr = 2+5+1;
687 else if (ch < 1000000)
688 incr = 2+6+1;
689 else {
690 assert(ch <= MAX_UNICODE);
691 incr = 2+7+1;
692 }
693 if (size > PY_SSIZE_T_MAX - incr) {
694 PyErr_SetString(PyExc_OverflowError,
695 "encoded result is too long for a Python string");
696 return NULL;
697 }
698 size += incr;
699 }
700
Victor Stinnerad771582015-10-09 12:38:53 +0200701 str = _PyBytesWriter_Prepare(writer, str, size);
702 if (str == NULL)
703 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200704
705 /* generate replacement */
706 for (i = collstart; i < collend; ++i) {
707 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
708 }
709 return str;
710}
711
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712/* --- Bloom Filters ----------------------------------------------------- */
713
714/* stuff to implement simple "bloom filters" for Unicode characters.
715 to keep things simple, we use a single bitmask, using the least 5
716 bits from each unicode characters as the bit index. */
717
718/* the linebreak mask is set up by Unicode_Init below */
719
Antoine Pitrouf068f942010-01-13 14:19:12 +0000720#if LONG_BIT >= 128
721#define BLOOM_WIDTH 128
722#elif LONG_BIT >= 64
723#define BLOOM_WIDTH 64
724#elif LONG_BIT >= 32
725#define BLOOM_WIDTH 32
726#else
727#error "LONG_BIT is smaller than 32"
728#endif
729
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730#define BLOOM_MASK unsigned long
731
Serhiy Storchaka05997252013-01-26 12:14:02 +0200732static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733
Antoine Pitrouf068f942010-01-13 14:19:12 +0000734#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735
Benjamin Peterson29060642009-01-31 22:14:21 +0000736#define BLOOM_LINEBREAK(ch) \
737 ((ch) < 128U ? ascii_linebreak[(ch)] : \
738 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700740static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742{
Victor Stinnera85af502013-04-09 21:53:54 +0200743#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
744 do { \
745 TYPE *data = (TYPE *)PTR; \
746 TYPE *end = data + LEN; \
747 Py_UCS4 ch; \
748 for (; data != end; data++) { \
749 ch = *data; \
750 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
751 } \
752 break; \
753 } while (0)
754
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755 /* calculate simple bloom-style bitmask for a given unicode string */
756
Antoine Pitrouf068f942010-01-13 14:19:12 +0000757 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
759 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200760 switch (kind) {
761 case PyUnicode_1BYTE_KIND:
762 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
763 break;
764 case PyUnicode_2BYTE_KIND:
765 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
766 break;
767 case PyUnicode_4BYTE_KIND:
768 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
769 break;
770 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700771 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200772 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200774
775#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776}
777
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300778static int
779ensure_unicode(PyObject *obj)
780{
781 if (!PyUnicode_Check(obj)) {
782 PyErr_Format(PyExc_TypeError,
783 "must be str, not %.100s",
784 Py_TYPE(obj)->tp_name);
785 return -1;
786 }
787 return PyUnicode_READY(obj);
788}
789
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200790/* Compilation of templated routines */
791
792#include "stringlib/asciilib.h"
793#include "stringlib/fastsearch.h"
794#include "stringlib/partition.h"
795#include "stringlib/split.h"
796#include "stringlib/count.h"
797#include "stringlib/find.h"
798#include "stringlib/find_max_char.h"
799#include "stringlib/localeutil.h"
800#include "stringlib/undef.h"
801
802#include "stringlib/ucs1lib.h"
803#include "stringlib/fastsearch.h"
804#include "stringlib/partition.h"
805#include "stringlib/split.h"
806#include "stringlib/count.h"
807#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300808#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200809#include "stringlib/find_max_char.h"
810#include "stringlib/localeutil.h"
811#include "stringlib/undef.h"
812
813#include "stringlib/ucs2lib.h"
814#include "stringlib/fastsearch.h"
815#include "stringlib/partition.h"
816#include "stringlib/split.h"
817#include "stringlib/count.h"
818#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300819#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200820#include "stringlib/find_max_char.h"
821#include "stringlib/localeutil.h"
822#include "stringlib/undef.h"
823
824#include "stringlib/ucs4lib.h"
825#include "stringlib/fastsearch.h"
826#include "stringlib/partition.h"
827#include "stringlib/split.h"
828#include "stringlib/count.h"
829#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300830#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200831#include "stringlib/find_max_char.h"
832#include "stringlib/localeutil.h"
833#include "stringlib/undef.h"
834
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200835#include "stringlib/unicodedefs.h"
836#include "stringlib/fastsearch.h"
837#include "stringlib/count.h"
838#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100839#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200840
Guido van Rossumd57fd912000-03-10 22:53:23 +0000841/* --- Unicode Object ----------------------------------------------------- */
842
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700843static inline Py_ssize_t
844findchar(const void *s, int kind,
845 Py_ssize_t size, Py_UCS4 ch,
846 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200847{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 switch (kind) {
849 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if ((Py_UCS1) ch != ch)
851 return -1;
852 if (direction > 0)
853 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
854 else
855 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200856 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200857 if ((Py_UCS2) ch != ch)
858 return -1;
859 if (direction > 0)
860 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
861 else
862 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200863 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200864 if (direction > 0)
865 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
866 else
867 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200868 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700869 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871}
872
Victor Stinnerafffce42012-10-03 23:03:17 +0200873#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000874/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200875 earlier.
876
877 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
878 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
879 invalid character in Unicode 6.0. */
880static void
881unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
882{
883 int kind = PyUnicode_KIND(unicode);
884 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
885 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
886 if (length <= old_length)
887 return;
888 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
889}
890#endif
891
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892static PyObject*
893resize_compact(PyObject *unicode, Py_ssize_t length)
894{
895 Py_ssize_t char_size;
896 Py_ssize_t struct_size;
897 Py_ssize_t new_size;
898 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100899 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200900#ifdef Py_DEBUG
901 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
902#endif
903
Victor Stinner79891572012-05-03 13:43:07 +0200904 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100906 assert(PyUnicode_IS_COMPACT(unicode));
907
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200908 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100909 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200910 struct_size = sizeof(PyASCIIObject);
911 else
912 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200913 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200914
Victor Stinnerfe226c02011-10-03 03:52:20 +0200915 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
916 PyErr_NoMemory();
917 return NULL;
918 }
919 new_size = (struct_size + (length + 1) * char_size);
920
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200921 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
922 PyObject_DEL(_PyUnicode_UTF8(unicode));
923 _PyUnicode_UTF8(unicode) = NULL;
924 _PyUnicode_UTF8_LENGTH(unicode) = 0;
925 }
Victor Stinner84def372011-12-11 20:04:56 +0100926 _Py_DEC_REFTOTAL;
927 _Py_ForgetReference(unicode);
928
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300929 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100930 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100931 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 PyErr_NoMemory();
933 return NULL;
934 }
Victor Stinner84def372011-12-11 20:04:56 +0100935 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200936 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100937
Victor Stinnerfe226c02011-10-03 03:52:20 +0200938 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200939 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100941 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 _PyUnicode_WSTR_LENGTH(unicode) = length;
943 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100944 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
945 PyObject_DEL(_PyUnicode_WSTR(unicode));
946 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100947 if (!PyUnicode_IS_ASCII(unicode))
948 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100949 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200950#ifdef Py_DEBUG
951 unicode_fill_invalid(unicode, old_length);
952#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
954 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200955 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 return unicode;
957}
958
Alexander Belopolsky40018472011-02-26 01:02:56 +0000959static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200960resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000961{
Victor Stinner95663112011-10-04 01:03:50 +0200962 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100963 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000966
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 if (PyUnicode_IS_READY(unicode)) {
968 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200969 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200970 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200971#ifdef Py_DEBUG
972 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
973#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974
975 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200976 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200977 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
978 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979
980 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 new_size = (length + 1) * char_size;
985
Victor Stinner7a9105a2011-12-12 00:13:42 +0100986 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
987 {
988 PyObject_DEL(_PyUnicode_UTF8(unicode));
989 _PyUnicode_UTF8(unicode) = NULL;
990 _PyUnicode_UTF8_LENGTH(unicode) = 0;
991 }
992
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 data = (PyObject *)PyObject_REALLOC(data, new_size);
994 if (data == NULL) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200999 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001001 _PyUnicode_WSTR_LENGTH(unicode) = length;
1002 }
1003 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001004 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001005 _PyUnicode_UTF8_LENGTH(unicode) = length;
1006 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001007 _PyUnicode_LENGTH(unicode) = length;
1008 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001009#ifdef Py_DEBUG
1010 unicode_fill_invalid(unicode, old_length);
1011#endif
Victor Stinner95663112011-10-04 01:03:50 +02001012 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001013 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001015 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001016 }
Victor Stinner95663112011-10-04 01:03:50 +02001017 assert(_PyUnicode_WSTR(unicode) != NULL);
1018
1019 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001020 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001021 PyErr_NoMemory();
1022 return -1;
1023 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001024 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001025 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001026 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001027 if (!wstr) {
1028 PyErr_NoMemory();
1029 return -1;
1030 }
1031 _PyUnicode_WSTR(unicode) = wstr;
1032 _PyUnicode_WSTR(unicode)[length] = 0;
1033 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001034 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001035 return 0;
1036}
1037
Victor Stinnerfe226c02011-10-03 03:52:20 +02001038static PyObject*
1039resize_copy(PyObject *unicode, Py_ssize_t length)
1040{
1041 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001042 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001045 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046
1047 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1048 if (copy == NULL)
1049 return NULL;
1050
1051 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001052 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001054 }
1055 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001056 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001057
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001058 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001059 if (w == NULL)
1060 return NULL;
1061 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1062 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001063 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001064 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001065 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001066 }
1067}
1068
Guido van Rossumd57fd912000-03-10 22:53:23 +00001069/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001070 Ux0000 terminated; some code (e.g. new_identifier)
1071 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072
1073 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001074 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075
1076*/
1077
Alexander Belopolsky40018472011-02-26 01:02:56 +00001078static PyUnicodeObject *
1079_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001080{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001081 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001083
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 if (length == 0 && unicode_empty != NULL) {
1086 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001087 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001088 }
1089
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001090 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001091 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001092 return (PyUnicodeObject *)PyErr_NoMemory();
1093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 if (length < 0) {
1095 PyErr_SetString(PyExc_SystemError,
1096 "Negative size passed to _PyUnicode_New");
1097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001098 }
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1101 if (unicode == NULL)
1102 return NULL;
1103 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001104
1105 _PyUnicode_WSTR_LENGTH(unicode) = length;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
1108 _PyUnicode_STATE(unicode).kind = 0;
1109 _PyUnicode_STATE(unicode).compact = 0;
1110 _PyUnicode_STATE(unicode).ready = 0;
1111 _PyUnicode_STATE(unicode).ascii = 0;
1112 _PyUnicode_DATA_ANY(unicode) = NULL;
1113 _PyUnicode_LENGTH(unicode) = 0;
1114 _PyUnicode_UTF8(unicode) = NULL;
1115 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1118 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001119 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001120 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001121 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123
Jeremy Hyltond8082792003-09-16 19:41:39 +00001124 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001125 * the caller fails before initializing str -- unicode_resize()
1126 * reads str[0], and the Keep-Alive optimization can keep memory
1127 * allocated for str alive across a call to unicode_dealloc(unicode).
1128 * We don't want unicode_resize to read uninitialized memory in
1129 * that case.
1130 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131 _PyUnicode_WSTR(unicode)[0] = 0;
1132 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001133
Victor Stinner7931d9a2011-11-04 00:22:48 +01001134 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001135 return unicode;
1136}
1137
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138static const char*
1139unicode_kind_name(PyObject *unicode)
1140{
Victor Stinner42dfd712011-10-03 14:41:45 +02001141 /* don't check consistency: unicode_kind_name() is called from
1142 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001143 if (!PyUnicode_IS_COMPACT(unicode))
1144 {
1145 if (!PyUnicode_IS_READY(unicode))
1146 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001147 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001148 {
1149 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001150 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 return "legacy ascii";
1152 else
1153 return "legacy latin1";
1154 case PyUnicode_2BYTE_KIND:
1155 return "legacy UCS2";
1156 case PyUnicode_4BYTE_KIND:
1157 return "legacy UCS4";
1158 default:
1159 return "<legacy invalid kind>";
1160 }
1161 }
1162 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001163 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001164 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001165 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001166 return "ascii";
1167 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001168 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001169 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001170 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001171 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001172 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 default:
1174 return "<invalid compact kind>";
1175 }
1176}
1177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179/* Functions wrapping macros for use in debugger */
1180char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001181 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001182}
1183
1184void *_PyUnicode_compact_data(void *unicode) {
1185 return _PyUnicode_COMPACT_DATA(unicode);
1186}
1187void *_PyUnicode_data(void *unicode){
1188 printf("obj %p\n", unicode);
1189 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1190 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1191 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1192 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1193 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1194 return PyUnicode_DATA(unicode);
1195}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001196
1197void
1198_PyUnicode_Dump(PyObject *op)
1199{
1200 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001201 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1202 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1203 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001206 {
1207 if (ascii->state.ascii)
1208 data = (ascii + 1);
1209 else
1210 data = (compact + 1);
1211 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001212 else
1213 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001214 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1215 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001216
Victor Stinnera849a4b2011-10-03 12:12:11 +02001217 if (ascii->wstr == data)
1218 printf("shared ");
1219 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001220
Victor Stinnera3b334d2011-10-03 13:53:37 +02001221 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001222 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001223 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1224 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001225 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1226 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001227 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001228 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001229}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230#endif
1231
1232PyObject *
1233PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1234{
1235 PyObject *obj;
1236 PyCompactUnicodeObject *unicode;
1237 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001238 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001239 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 Py_ssize_t char_size;
1241 Py_ssize_t struct_size;
1242
1243 /* Optimization for empty strings */
1244 if (size == 0 && unicode_empty != NULL) {
1245 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001246 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 }
1248
Victor Stinner9e9d6892011-10-04 01:02:02 +02001249 is_ascii = 0;
1250 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 struct_size = sizeof(PyCompactUnicodeObject);
1252 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001253 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 char_size = 1;
1255 is_ascii = 1;
1256 struct_size = sizeof(PyASCIIObject);
1257 }
1258 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001259 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 char_size = 1;
1261 }
1262 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001263 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 char_size = 2;
1265 if (sizeof(wchar_t) == 2)
1266 is_sharing = 1;
1267 }
1268 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001269 if (maxchar > MAX_UNICODE) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "invalid maximum character passed to PyUnicode_New");
1272 return NULL;
1273 }
Victor Stinner8f825062012-04-27 13:55:39 +02001274 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 char_size = 4;
1276 if (sizeof(wchar_t) == 4)
1277 is_sharing = 1;
1278 }
1279
1280 /* Ensure we won't overflow the size. */
1281 if (size < 0) {
1282 PyErr_SetString(PyExc_SystemError,
1283 "Negative size passed to PyUnicode_New");
1284 return NULL;
1285 }
1286 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1287 return PyErr_NoMemory();
1288
1289 /* Duplicated allocation code from _PyObject_New() instead of a call to
1290 * PyObject_New() so we are able to allocate space for the object and
1291 * it's data buffer.
1292 */
1293 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1294 if (obj == NULL)
1295 return PyErr_NoMemory();
1296 obj = PyObject_INIT(obj, &PyUnicode_Type);
1297 if (obj == NULL)
1298 return NULL;
1299
1300 unicode = (PyCompactUnicodeObject *)obj;
1301 if (is_ascii)
1302 data = ((PyASCIIObject*)obj) + 1;
1303 else
1304 data = unicode + 1;
1305 _PyUnicode_LENGTH(unicode) = size;
1306 _PyUnicode_HASH(unicode) = -1;
1307 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001308 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 _PyUnicode_STATE(unicode).compact = 1;
1310 _PyUnicode_STATE(unicode).ready = 1;
1311 _PyUnicode_STATE(unicode).ascii = is_ascii;
1312 if (is_ascii) {
1313 ((char*)data)[size] = 0;
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 }
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((char*)data)[size] = 0;
1318 _PyUnicode_WSTR(unicode) = NULL;
1319 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001321 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 else {
1324 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001325 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001326 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001328 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001329 ((Py_UCS4*)data)[size] = 0;
1330 if (is_sharing) {
1331 _PyUnicode_WSTR_LENGTH(unicode) = size;
1332 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1333 }
1334 else {
1335 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1336 _PyUnicode_WSTR(unicode) = NULL;
1337 }
1338 }
Victor Stinner8f825062012-04-27 13:55:39 +02001339#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001340 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001341#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001342 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 return obj;
1344}
1345
1346#if SIZEOF_WCHAR_T == 2
1347/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1348 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001349 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350
1351 This function assumes that unicode can hold one more code point than wstr
1352 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001353static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001355 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356{
1357 const wchar_t *iter;
1358 Py_UCS4 *ucs4_out;
1359
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(unicode != NULL);
1361 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1363 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1364
1365 for (iter = begin; iter < end; ) {
1366 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1367 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001368 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1369 && (iter+1) < end
1370 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 {
Victor Stinner551ac952011-11-29 22:58:13 +01001372 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 iter += 2;
1374 }
1375 else {
1376 *ucs4_out++ = *iter;
1377 iter++;
1378 }
1379 }
1380 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1381 _PyUnicode_GET_LENGTH(unicode)));
1382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383}
1384#endif
1385
Victor Stinnercd9950f2011-10-02 00:34:53 +02001386static int
Victor Stinner488fa492011-12-12 00:01:39 +01001387unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001388{
Victor Stinner488fa492011-12-12 00:01:39 +01001389 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001390 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001391 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001392 return -1;
1393 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001394 return 0;
1395}
1396
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397static int
1398_copy_characters(PyObject *to, Py_ssize_t to_start,
1399 PyObject *from, Py_ssize_t from_start,
1400 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001402 unsigned int from_kind, to_kind;
1403 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404
Victor Stinneree4544c2012-05-09 22:24:08 +02001405 assert(0 <= how_many);
1406 assert(0 <= from_start);
1407 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001408 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001409 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001410 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerd3f08822012-05-29 12:57:52 +02001412 assert(PyUnicode_Check(to));
1413 assert(PyUnicode_IS_READY(to));
1414 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1415
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001416 if (how_many == 0)
1417 return 0;
1418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001420 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423
Victor Stinnerf1852262012-06-16 16:38:26 +02001424#ifdef Py_DEBUG
1425 if (!check_maxchar
1426 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1427 {
1428 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1429 Py_UCS4 ch;
1430 Py_ssize_t i;
1431 for (i=0; i < how_many; i++) {
1432 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1433 assert(ch <= to_maxchar);
1434 }
1435 }
1436#endif
1437
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001438 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001439 if (check_maxchar
1440 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1441 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001442 /* Writing Latin-1 characters into an ASCII string requires to
1443 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001444 Py_UCS4 max_char;
1445 max_char = ucs1lib_find_max_char(from_data,
1446 (Py_UCS1*)from_data + how_many);
1447 if (max_char >= 128)
1448 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001449 }
Christian Heimesf051e432016-09-13 20:22:02 +02001450 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001451 (char*)from_data + from_kind * from_start,
1452 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001454 else if (from_kind == PyUnicode_1BYTE_KIND
1455 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS1, Py_UCS2,
1459 PyUnicode_1BYTE_DATA(from) + from_start,
1460 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_2BYTE_DATA(to) + to_start
1462 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001463 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001464 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001465 && to_kind == PyUnicode_4BYTE_KIND)
1466 {
1467 _PyUnicode_CONVERT_BYTES(
1468 Py_UCS1, Py_UCS4,
1469 PyUnicode_1BYTE_DATA(from) + from_start,
1470 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1471 PyUnicode_4BYTE_DATA(to) + to_start
1472 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001473 }
1474 else if (from_kind == PyUnicode_2BYTE_KIND
1475 && to_kind == PyUnicode_4BYTE_KIND)
1476 {
1477 _PyUnicode_CONVERT_BYTES(
1478 Py_UCS2, Py_UCS4,
1479 PyUnicode_2BYTE_DATA(from) + from_start,
1480 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1481 PyUnicode_4BYTE_DATA(to) + to_start
1482 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001483 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001484 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001485 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1486
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001487 if (!check_maxchar) {
1488 if (from_kind == PyUnicode_2BYTE_KIND
1489 && to_kind == PyUnicode_1BYTE_KIND)
1490 {
1491 _PyUnicode_CONVERT_BYTES(
1492 Py_UCS2, Py_UCS1,
1493 PyUnicode_2BYTE_DATA(from) + from_start,
1494 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1495 PyUnicode_1BYTE_DATA(to) + to_start
1496 );
1497 }
1498 else if (from_kind == PyUnicode_4BYTE_KIND
1499 && to_kind == PyUnicode_1BYTE_KIND)
1500 {
1501 _PyUnicode_CONVERT_BYTES(
1502 Py_UCS4, Py_UCS1,
1503 PyUnicode_4BYTE_DATA(from) + from_start,
1504 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1505 PyUnicode_1BYTE_DATA(to) + to_start
1506 );
1507 }
1508 else if (from_kind == PyUnicode_4BYTE_KIND
1509 && to_kind == PyUnicode_2BYTE_KIND)
1510 {
1511 _PyUnicode_CONVERT_BYTES(
1512 Py_UCS4, Py_UCS2,
1513 PyUnicode_4BYTE_DATA(from) + from_start,
1514 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1515 PyUnicode_2BYTE_DATA(to) + to_start
1516 );
1517 }
1518 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001519 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001520 }
1521 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001522 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001523 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001525 Py_ssize_t i;
1526
Victor Stinnera0702ab2011-09-29 14:14:38 +02001527 for (i=0; i < how_many; i++) {
1528 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001529 if (ch > to_maxchar)
1530 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001531 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1532 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001533 }
1534 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001535 return 0;
1536}
1537
Victor Stinnerd3f08822012-05-29 12:57:52 +02001538void
1539_PyUnicode_FastCopyCharacters(
1540 PyObject *to, Py_ssize_t to_start,
1541 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001542{
1543 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1544}
1545
1546Py_ssize_t
1547PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1548 PyObject *from, Py_ssize_t from_start,
1549 Py_ssize_t how_many)
1550{
1551 int err;
1552
1553 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1554 PyErr_BadInternalCall();
1555 return -1;
1556 }
1557
Benjamin Petersonbac79492012-01-14 13:34:47 -05001558 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001560 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001561 return -1;
1562
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001563 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001564 PyErr_SetString(PyExc_IndexError, "string index out of range");
1565 return -1;
1566 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001567 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568 PyErr_SetString(PyExc_IndexError, "string index out of range");
1569 return -1;
1570 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001571 if (how_many < 0) {
1572 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1573 return -1;
1574 }
1575 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1577 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001578 "Cannot write %zi characters at %zi "
1579 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001580 how_many, to_start, PyUnicode_GET_LENGTH(to));
1581 return -1;
1582 }
1583
1584 if (how_many == 0)
1585 return 0;
1586
Victor Stinner488fa492011-12-12 00:01:39 +01001587 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001588 return -1;
1589
1590 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1591 if (err) {
1592 PyErr_Format(PyExc_SystemError,
1593 "Cannot copy %s characters "
1594 "into a string of %s characters",
1595 unicode_kind_name(from),
1596 unicode_kind_name(to));
1597 return -1;
1598 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001599 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600}
1601
Victor Stinner17222162011-09-28 22:15:37 +02001602/* Find the maximum code point and count the number of surrogate pairs so a
1603 correct string length can be computed before converting a string to UCS4.
1604 This function counts single surrogates as a character and not as a pair.
1605
1606 Return 0 on success, or -1 on error. */
1607static int
1608find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1609 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610{
1611 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001612 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613
Victor Stinnerc53be962011-10-02 21:33:54 +02001614 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 *num_surrogates = 0;
1616 *maxchar = 0;
1617
1618 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001620 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1621 && (iter+1) < end
1622 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1623 {
1624 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1625 ++(*num_surrogates);
1626 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001630 {
1631 ch = *iter;
1632 iter++;
1633 }
1634 if (ch > *maxchar) {
1635 *maxchar = ch;
1636 if (*maxchar > MAX_UNICODE) {
1637 PyErr_Format(PyExc_ValueError,
1638 "character U+%x is not in range [U+0000; U+10ffff]",
1639 ch);
1640 return -1;
1641 }
1642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 }
1644 return 0;
1645}
1646
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001647int
1648_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649{
1650 wchar_t *end;
1651 Py_UCS4 maxchar = 0;
1652 Py_ssize_t num_surrogates;
1653#if SIZEOF_WCHAR_T == 2
1654 Py_ssize_t length_wo_surrogates;
1655#endif
1656
Georg Brandl7597add2011-10-05 16:36:47 +02001657 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001658 strings were created using _PyObject_New() and where no canonical
1659 representation (the str field) has been set yet aka strings
1660 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001661 assert(_PyUnicode_CHECK(unicode));
1662 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001665 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001666 /* Actually, it should neither be interned nor be anything else: */
1667 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001670 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001671 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673
1674 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001675 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1676 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 PyErr_NoMemory();
1678 return -1;
1679 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001680 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001681 _PyUnicode_WSTR(unicode), end,
1682 PyUnicode_1BYTE_DATA(unicode));
1683 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1684 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1685 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1686 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001687 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001688 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001689 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 }
1691 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001692 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001695 }
1696 PyObject_FREE(_PyUnicode_WSTR(unicode));
1697 _PyUnicode_WSTR(unicode) = NULL;
1698 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1699 }
1700 /* In this case we might have to convert down from 4-byte native
1701 wchar_t to 2-byte unicode. */
1702 else if (maxchar < 65536) {
1703 assert(num_surrogates == 0 &&
1704 "FindMaxCharAndNumSurrogatePairs() messed up");
1705
Victor Stinner506f5922011-09-28 22:34:18 +02001706#if SIZEOF_WCHAR_T == 2
1707 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001709 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1710 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1711 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001712 _PyUnicode_UTF8(unicode) = NULL;
1713 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001714#else
1715 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001716 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001717 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001718 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyErr_NoMemory();
1720 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 }
Victor Stinner506f5922011-09-28 22:34:18 +02001722 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1723 _PyUnicode_WSTR(unicode), end,
1724 PyUnicode_2BYTE_DATA(unicode));
1725 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1726 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1727 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001728 _PyUnicode_UTF8(unicode) = NULL;
1729 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001730 PyObject_FREE(_PyUnicode_WSTR(unicode));
1731 _PyUnicode_WSTR(unicode) = NULL;
1732 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1733#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 }
1735 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1736 else {
1737#if SIZEOF_WCHAR_T == 2
1738 /* in case the native representation is 2-bytes, we need to allocate a
1739 new normalized 4-byte version. */
1740 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001741 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1742 PyErr_NoMemory();
1743 return -1;
1744 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001745 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1746 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyErr_NoMemory();
1748 return -1;
1749 }
1750 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001752 _PyUnicode_UTF8(unicode) = NULL;
1753 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001754 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001756 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 PyObject_FREE(_PyUnicode_WSTR(unicode));
1758 _PyUnicode_WSTR(unicode) = NULL;
1759 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1760#else
1761 assert(num_surrogates == 0);
1762
Victor Stinnerc3c74152011-10-02 20:39:55 +02001763 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001765 _PyUnicode_UTF8(unicode) = NULL;
1766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1768#endif
1769 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1770 }
1771 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001772 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 return 0;
1774}
1775
Alexander Belopolsky40018472011-02-26 01:02:56 +00001776static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001777unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001778{
Walter Dörwald16807132007-05-25 13:52:07 +00001779 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_NOT_INTERNED:
1781 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 case SSTATE_INTERNED_MORTAL:
1784 /* revive dead object temporarily for DelItem */
1785 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001786 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001787 Py_FatalError(
1788 "deletion of interned string failed");
1789 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001790
Benjamin Peterson29060642009-01-31 22:14:21 +00001791 case SSTATE_INTERNED_IMMORTAL:
1792 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001793 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001794
Benjamin Peterson29060642009-01-31 22:14:21 +00001795 default:
1796 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001797 }
1798
Victor Stinner03490912011-10-03 23:45:12 +02001799 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001801 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001802 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001803 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1804 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001806 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807}
1808
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001809#ifdef Py_DEBUG
1810static int
1811unicode_is_singleton(PyObject *unicode)
1812{
1813 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1814 if (unicode == unicode_empty)
1815 return 1;
1816 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1817 {
1818 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1819 if (ch < 256 && unicode_latin1[ch] == unicode)
1820 return 1;
1821 }
1822 return 0;
1823}
1824#endif
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826static int
Victor Stinner488fa492011-12-12 00:01:39 +01001827unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828{
Victor Stinner488fa492011-12-12 00:01:39 +01001829 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 if (Py_REFCNT(unicode) != 1)
1831 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001832 if (_PyUnicode_HASH(unicode) != -1)
1833 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001834 if (PyUnicode_CHECK_INTERNED(unicode))
1835 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001836 if (!PyUnicode_CheckExact(unicode))
1837 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001838#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001839 /* singleton refcount is greater than 1 */
1840 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001841#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 return 1;
1843}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845static int
1846unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1847{
1848 PyObject *unicode;
1849 Py_ssize_t old_length;
1850
1851 assert(p_unicode != NULL);
1852 unicode = *p_unicode;
1853
1854 assert(unicode != NULL);
1855 assert(PyUnicode_Check(unicode));
1856 assert(0 <= length);
1857
Victor Stinner910337b2011-10-03 03:20:16 +02001858 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 old_length = PyUnicode_WSTR_LENGTH(unicode);
1860 else
1861 old_length = PyUnicode_GET_LENGTH(unicode);
1862 if (old_length == length)
1863 return 0;
1864
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001865 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001866 _Py_INCREF_UNICODE_EMPTY();
1867 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001868 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001869 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001870 return 0;
1871 }
1872
Victor Stinner488fa492011-12-12 00:01:39 +01001873 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 PyObject *copy = resize_copy(unicode, length);
1875 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001877 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001878 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001879 }
1880
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001882 PyObject *new_unicode = resize_compact(unicode, length);
1883 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001885 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001886 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001887 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001888 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001889}
1890
Alexander Belopolsky40018472011-02-26 01:02:56 +00001891int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001892PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001894 PyObject *unicode;
1895 if (p_unicode == NULL) {
1896 PyErr_BadInternalCall();
1897 return -1;
1898 }
1899 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001900 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001901 {
1902 PyErr_BadInternalCall();
1903 return -1;
1904 }
1905 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001906}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001907
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001908/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001909
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001910 WARNING: The function doesn't copy the terminating null character and
1911 doesn't check the maximum character (may write a latin1 character in an
1912 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001913static void
1914unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1915 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001916{
1917 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1918 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001919 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001920
1921 switch (kind) {
1922 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001923 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001924#ifdef Py_DEBUG
1925 if (PyUnicode_IS_ASCII(unicode)) {
1926 Py_UCS4 maxchar = ucs1lib_find_max_char(
1927 (const Py_UCS1*)str,
1928 (const Py_UCS1*)str + len);
1929 assert(maxchar < 128);
1930 }
1931#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001932 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001933 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001934 }
1935 case PyUnicode_2BYTE_KIND: {
1936 Py_UCS2 *start = (Py_UCS2 *)data + index;
1937 Py_UCS2 *ucs2 = start;
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs2 = (Py_UCS2)*str;
1942
1943 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001944 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001945 }
1946 default: {
1947 Py_UCS4 *start = (Py_UCS4 *)data + index;
1948 Py_UCS4 *ucs4 = start;
1949 assert(kind == PyUnicode_4BYTE_KIND);
1950 assert(index <= PyUnicode_GET_LENGTH(unicode));
1951
Victor Stinner184252a2012-06-16 02:57:41 +02001952 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001953 *ucs4 = (Py_UCS4)*str;
1954
1955 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001956 }
1957 }
1958}
1959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960static PyObject*
1961get_latin1_char(unsigned char ch)
1962{
Victor Stinnera464fc12011-10-02 20:39:30 +02001963 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001964 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001965 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 if (!unicode)
1967 return NULL;
1968 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001969 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001970 unicode_latin1[ch] = unicode;
1971 }
1972 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001973 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974}
1975
Victor Stinner985a82a2014-01-03 12:53:47 +01001976static PyObject*
1977unicode_char(Py_UCS4 ch)
1978{
1979 PyObject *unicode;
1980
1981 assert(ch <= MAX_UNICODE);
1982
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001983 if (ch < 256)
1984 return get_latin1_char(ch);
1985
Victor Stinner985a82a2014-01-03 12:53:47 +01001986 unicode = PyUnicode_New(1, ch);
1987 if (unicode == NULL)
1988 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001989
1990 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1991 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001992 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001993 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001994 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1995 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1996 }
1997 assert(_PyUnicode_CheckConsistency(unicode, 1));
1998 return unicode;
1999}
2000
Alexander Belopolsky40018472011-02-26 01:02:56 +00002001PyObject *
2002PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002003{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002004 if (u == NULL)
2005 return (PyObject*)_PyUnicode_New(size);
2006
2007 if (size < 0) {
2008 PyErr_BadInternalCall();
2009 return NULL;
2010 }
2011
2012 return PyUnicode_FromWideChar(u, size);
2013}
2014
2015PyObject *
2016PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2017{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002018 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 Py_UCS4 maxchar = 0;
2020 Py_ssize_t num_surrogates;
2021
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002022 if (u == NULL && size != 0) {
2023 PyErr_BadInternalCall();
2024 return NULL;
2025 }
2026
2027 if (size == -1) {
2028 size = wcslen(u);
2029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002030
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002031 /* If the Unicode data is known at construction time, we can apply
2032 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002035 if (size == 0)
2036 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 /* Single character Unicode objects in the Latin-1 range are
2039 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002040 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return get_latin1_char((unsigned char)*u);
2042
2043 /* If not empty and not single character, copy the Unicode data
2044 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002045 if (find_maxchar_surrogates(u, u + size,
2046 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048
Victor Stinner8faf8212011-12-08 22:14:11 +01002049 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 if (!unicode)
2051 return NULL;
2052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 switch (PyUnicode_KIND(unicode)) {
2054 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002055 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2057 break;
2058 case PyUnicode_2BYTE_KIND:
2059#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002060 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002062 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2064#endif
2065 break;
2066 case PyUnicode_4BYTE_KIND:
2067#if SIZEOF_WCHAR_T == 2
2068 /* This is the only case which has to process surrogates, thus
2069 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002070 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071#else
2072 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002073 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074#endif
2075 break;
2076 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002077 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002080 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081}
2082
Alexander Belopolsky40018472011-02-26 01:02:56 +00002083PyObject *
2084PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002085{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002086 if (size < 0) {
2087 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002088 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002089 return NULL;
2090 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002091 if (u != NULL)
2092 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2093 else
2094 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002095}
2096
Alexander Belopolsky40018472011-02-26 01:02:56 +00002097PyObject *
2098PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002099{
2100 size_t size = strlen(u);
2101 if (size > PY_SSIZE_T_MAX) {
2102 PyErr_SetString(PyExc_OverflowError, "input too long");
2103 return NULL;
2104 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002105 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002106}
2107
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002108PyObject *
2109_PyUnicode_FromId(_Py_Identifier *id)
2110{
2111 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002112 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2113 strlen(id->string),
2114 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002115 if (!id->object)
2116 return NULL;
2117 PyUnicode_InternInPlace(&id->object);
2118 assert(!id->next);
2119 id->next = static_strings;
2120 static_strings = id;
2121 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002122 return id->object;
2123}
2124
2125void
2126_PyUnicode_ClearStaticStrings()
2127{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002128 _Py_Identifier *tmp, *s = static_strings;
2129 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002130 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002131 tmp = s->next;
2132 s->next = NULL;
2133 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002134 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002135 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002136}
2137
Benjamin Peterson0df54292012-03-26 14:50:32 -04002138/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139
Victor Stinnerd3f08822012-05-29 12:57:52 +02002140PyObject*
2141_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002142{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002143 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002144 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002145 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002146#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002147 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002148#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002149 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002150 }
Victor Stinner785938e2011-12-11 20:09:03 +01002151 unicode = PyUnicode_New(size, 127);
2152 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002153 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002154 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2155 assert(_PyUnicode_CheckConsistency(unicode, 1));
2156 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002157}
2158
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159static Py_UCS4
2160kind_maxchar_limit(unsigned int kind)
2161{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002162 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002163 case PyUnicode_1BYTE_KIND:
2164 return 0x80;
2165 case PyUnicode_2BYTE_KIND:
2166 return 0x100;
2167 case PyUnicode_4BYTE_KIND:
2168 return 0x10000;
2169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002171 }
2172}
2173
Victor Stinner702c7342011-10-05 13:50:52 +02002174static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002175_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002178 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002179
Serhiy Storchaka678db842013-01-26 12:16:36 +02002180 if (size == 0)
2181 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002182 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002183 if (size == 1)
2184 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002185
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002186 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 if (!res)
2189 return NULL;
2190 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002191 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002193}
2194
Victor Stinnere57b1c02011-09-28 22:20:48 +02002195static PyObject*
2196_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197{
2198 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002199 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002200
Serhiy Storchaka678db842013-01-26 12:16:36 +02002201 if (size == 0)
2202 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002203 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002204 if (size == 1)
2205 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002207 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002208 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 if (!res)
2210 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 else {
2214 _PyUnicode_CONVERT_BYTES(
2215 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2216 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002217 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return res;
2219}
2220
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221static PyObject*
2222_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223{
2224 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002225 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002226
Serhiy Storchaka678db842013-01-26 12:16:36 +02002227 if (size == 0)
2228 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002229 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002230 if (size == 1)
2231 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002233 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002234 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 if (!res)
2236 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002237 if (max_char < 256)
2238 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2239 PyUnicode_1BYTE_DATA(res));
2240 else if (max_char < 0x10000)
2241 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2242 PyUnicode_2BYTE_DATA(res));
2243 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002245 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 return res;
2247}
2248
2249PyObject*
2250PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2251{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002252 if (size < 0) {
2253 PyErr_SetString(PyExc_ValueError, "size must be positive");
2254 return NULL;
2255 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002256 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002258 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002260 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002262 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002263 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002264 PyErr_SetString(PyExc_SystemError, "invalid kind");
2265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267}
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269Py_UCS4
2270_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2271{
2272 enum PyUnicode_Kind kind;
2273 void *startptr, *endptr;
2274
2275 assert(PyUnicode_IS_READY(unicode));
2276 assert(0 <= start);
2277 assert(end <= PyUnicode_GET_LENGTH(unicode));
2278 assert(start <= end);
2279
2280 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2281 return PyUnicode_MAX_CHAR_VALUE(unicode);
2282
2283 if (start == end)
2284 return 127;
2285
Victor Stinner94d558b2012-04-27 22:26:58 +02002286 if (PyUnicode_IS_ASCII(unicode))
2287 return 127;
2288
Victor Stinnerece58de2012-04-23 23:36:38 +02002289 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002290 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002291 endptr = (char *)startptr + end * kind;
2292 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002293 switch(kind) {
2294 case PyUnicode_1BYTE_KIND:
2295 return ucs1lib_find_max_char(startptr, endptr);
2296 case PyUnicode_2BYTE_KIND:
2297 return ucs2lib_find_max_char(startptr, endptr);
2298 case PyUnicode_4BYTE_KIND:
2299 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002301 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002302 }
2303}
2304
Victor Stinner25a4b292011-10-06 12:31:55 +02002305/* Ensure that a string uses the most efficient storage, if it is not the
2306 case: create a new string with of the right kind. Write NULL into *p_unicode
2307 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002308static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002309unicode_adjust_maxchar(PyObject **p_unicode)
2310{
2311 PyObject *unicode, *copy;
2312 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002314 unsigned int kind;
2315
2316 assert(p_unicode != NULL);
2317 unicode = *p_unicode;
2318 assert(PyUnicode_IS_READY(unicode));
2319 if (PyUnicode_IS_ASCII(unicode))
2320 return;
2321
2322 len = PyUnicode_GET_LENGTH(unicode);
2323 kind = PyUnicode_KIND(unicode);
2324 if (kind == PyUnicode_1BYTE_KIND) {
2325 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002326 max_char = ucs1lib_find_max_char(u, u + len);
2327 if (max_char >= 128)
2328 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 }
2330 else if (kind == PyUnicode_2BYTE_KIND) {
2331 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002332 max_char = ucs2lib_find_max_char(u, u + len);
2333 if (max_char >= 256)
2334 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002335 }
2336 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002337 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002338 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002339 max_char = ucs4lib_find_max_char(u, u + len);
2340 if (max_char >= 0x10000)
2341 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002342 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002343 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002344 if (copy != NULL)
2345 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002346 Py_DECREF(unicode);
2347 *p_unicode = copy;
2348}
2349
Victor Stinner034f6cf2011-09-30 02:26:44 +02002350PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002351_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002352{
Victor Stinner87af4f22011-11-21 23:03:47 +01002353 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002355
Victor Stinner034f6cf2011-09-30 02:26:44 +02002356 if (!PyUnicode_Check(unicode)) {
2357 PyErr_BadInternalCall();
2358 return NULL;
2359 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002360 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002361 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002362
Victor Stinner87af4f22011-11-21 23:03:47 +01002363 length = PyUnicode_GET_LENGTH(unicode);
2364 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002365 if (!copy)
2366 return NULL;
2367 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2368
Christian Heimesf051e432016-09-13 20:22:02 +02002369 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002370 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002371 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002372 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002373}
2374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375
Victor Stinnerbc603d12011-10-02 01:00:40 +02002376/* Widen Unicode objects to larger buffers. Don't write terminating null
2377 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002378
2379void*
2380_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2381{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 Py_ssize_t len;
2383 void *result;
2384 unsigned int skind;
2385
Benjamin Petersonbac79492012-01-14 13:34:47 -05002386 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002387 return NULL;
2388
2389 len = PyUnicode_GET_LENGTH(s);
2390 skind = PyUnicode_KIND(s);
2391 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002395 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002396 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002397 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002398 if (!result)
2399 return PyErr_NoMemory();
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS2,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002407 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002408 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 if (!result)
2410 return PyErr_NoMemory();
2411 if (skind == PyUnicode_2BYTE_KIND) {
2412 _PyUnicode_CONVERT_BYTES(
2413 Py_UCS2, Py_UCS4,
2414 PyUnicode_2BYTE_DATA(s),
2415 PyUnicode_2BYTE_DATA(s) + len,
2416 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002418 else {
2419 assert(skind == PyUnicode_1BYTE_KIND);
2420 _PyUnicode_CONVERT_BYTES(
2421 Py_UCS1, Py_UCS4,
2422 PyUnicode_1BYTE_DATA(s),
2423 PyUnicode_1BYTE_DATA(s) + len,
2424 result);
2425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002427 default:
2428 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 }
Victor Stinner01698042011-10-04 00:04:26 +02002430 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 return NULL;
2432}
2433
2434static Py_UCS4*
2435as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2436 int copy_null)
2437{
2438 int kind;
2439 void *data;
2440 Py_ssize_t len, targetlen;
2441 if (PyUnicode_READY(string) == -1)
2442 return NULL;
2443 kind = PyUnicode_KIND(string);
2444 data = PyUnicode_DATA(string);
2445 len = PyUnicode_GET_LENGTH(string);
2446 targetlen = len;
2447 if (copy_null)
2448 targetlen++;
2449 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002450 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 if (!target) {
2452 PyErr_NoMemory();
2453 return NULL;
2454 }
2455 }
2456 else {
2457 if (targetsize < targetlen) {
2458 PyErr_Format(PyExc_SystemError,
2459 "string is longer than the buffer");
2460 if (copy_null && 0 < targetsize)
2461 target[0] = 0;
2462 return NULL;
2463 }
2464 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002465 if (kind == PyUnicode_1BYTE_KIND) {
2466 Py_UCS1 *start = (Py_UCS1 *) data;
2467 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002469 else if (kind == PyUnicode_2BYTE_KIND) {
2470 Py_UCS2 *start = (Py_UCS2 *) data;
2471 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2472 }
2473 else {
2474 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002475 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 if (copy_null)
2478 target[len] = 0;
2479 return target;
2480}
2481
2482Py_UCS4*
2483PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2484 int copy_null)
2485{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002486 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 PyErr_BadInternalCall();
2488 return NULL;
2489 }
2490 return as_ucs4(string, target, targetsize, copy_null);
2491}
2492
2493Py_UCS4*
2494PyUnicode_AsUCS4Copy(PyObject *string)
2495{
2496 return as_ucs4(string, NULL, 0, 1);
2497}
2498
Victor Stinner15a11362012-10-06 23:48:20 +02002499/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002500 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2501 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2502#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002503
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002504static int
2505unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2506 Py_ssize_t width, Py_ssize_t precision)
2507{
2508 Py_ssize_t length, fill, arglen;
2509 Py_UCS4 maxchar;
2510
2511 if (PyUnicode_READY(str) == -1)
2512 return -1;
2513
2514 length = PyUnicode_GET_LENGTH(str);
2515 if ((precision == -1 || precision >= length)
2516 && width <= length)
2517 return _PyUnicodeWriter_WriteStr(writer, str);
2518
2519 if (precision != -1)
2520 length = Py_MIN(precision, length);
2521
2522 arglen = Py_MAX(length, width);
2523 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2524 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2525 else
2526 maxchar = writer->maxchar;
2527
2528 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2529 return -1;
2530
2531 if (width > length) {
2532 fill = width - length;
2533 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2534 return -1;
2535 writer->pos += fill;
2536 }
2537
2538 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2539 str, 0, length);
2540 writer->pos += length;
2541 return 0;
2542}
2543
2544static int
2545unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2546 Py_ssize_t width, Py_ssize_t precision)
2547{
2548 /* UTF-8 */
2549 Py_ssize_t length;
2550 PyObject *unicode;
2551 int res;
2552
2553 length = strlen(str);
2554 if (precision != -1)
2555 length = Py_MIN(length, precision);
2556 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2557 if (unicode == NULL)
2558 return -1;
2559
2560 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2561 Py_DECREF(unicode);
2562 return res;
2563}
2564
Victor Stinner96865452011-03-01 23:44:09 +00002565static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002566unicode_fromformat_arg(_PyUnicodeWriter *writer,
2567 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002568{
Victor Stinnere215d962012-10-06 23:03:36 +02002569 const char *p;
2570 Py_ssize_t len;
2571 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 Py_ssize_t width;
2573 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002574 int longflag;
2575 int longlongflag;
2576 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002577 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002578
2579 p = f;
2580 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002581 zeropad = 0;
2582 if (*f == '0') {
2583 zeropad = 1;
2584 f++;
2585 }
Victor Stinner96865452011-03-01 23:44:09 +00002586
2587 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 width = -1;
2589 if (Py_ISDIGIT((unsigned)*f)) {
2590 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002591 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002592 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002594 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002596 return NULL;
2597 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002599 f++;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 }
2602 precision = -1;
2603 if (*f == '.') {
2604 f++;
2605 if (Py_ISDIGIT((unsigned)*f)) {
2606 precision = (*f - '0');
2607 f++;
2608 while (Py_ISDIGIT((unsigned)*f)) {
2609 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2610 PyErr_SetString(PyExc_ValueError,
2611 "precision too big");
2612 return NULL;
2613 }
2614 precision = (precision * 10) + (*f - '0');
2615 f++;
2616 }
2617 }
Victor Stinner96865452011-03-01 23:44:09 +00002618 if (*f == '%') {
2619 /* "%.3%s" => f points to "3" */
2620 f--;
2621 }
2622 }
2623 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002624 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002625 f--;
2626 }
Victor Stinner96865452011-03-01 23:44:09 +00002627
2628 /* Handle %ld, %lu, %lld and %llu. */
2629 longflag = 0;
2630 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002631 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002632 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002633 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002634 longflag = 1;
2635 ++f;
2636 }
Victor Stinner96865452011-03-01 23:44:09 +00002637 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002639 longlongflag = 1;
2640 f += 2;
2641 }
Victor Stinner96865452011-03-01 23:44:09 +00002642 }
2643 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002644 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002645 size_tflag = 1;
2646 ++f;
2647 }
Victor Stinnere215d962012-10-06 23:03:36 +02002648
2649 if (f[1] == '\0')
2650 writer->overallocate = 0;
2651
2652 switch (*f) {
2653 case 'c':
2654 {
2655 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002656 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002657 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 "character argument not in range(0x110000)");
2659 return NULL;
2660 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002661 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002662 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002663 break;
2664 }
2665
2666 case 'i':
2667 case 'd':
2668 case 'u':
2669 case 'x':
2670 {
2671 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002672 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002673 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002674
2675 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002676 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002678 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002679 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002680 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002681 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002683 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002684 va_arg(*vargs, size_t));
2685 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, unsigned int));
2688 }
2689 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002691 }
2692 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002694 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002695 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002696 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002697 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002698 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002700 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002701 va_arg(*vargs, Py_ssize_t));
2702 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, int));
2705 }
2706 assert(len >= 0);
2707
Victor Stinnere215d962012-10-06 23:03:36 +02002708 if (precision < len)
2709 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002710
2711 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2713 return NULL;
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (width > precision) {
2716 Py_UCS4 fillchar;
2717 fill = width - precision;
2718 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002719 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2720 return NULL;
2721 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002722 }
Victor Stinner15a11362012-10-06 23:48:20 +02002723 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002724 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2726 return NULL;
2727 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002728 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002729
Victor Stinner4a587072013-11-19 12:54:53 +01002730 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2731 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002732 break;
2733 }
2734
2735 case 'p':
2736 {
2737 char number[MAX_LONG_LONG_CHARS];
2738
2739 len = sprintf(number, "%p", va_arg(*vargs, void*));
2740 assert(len >= 0);
2741
2742 /* %p is ill-defined: ensure leading 0x. */
2743 if (number[1] == 'X')
2744 number[1] = 'x';
2745 else if (number[1] != 'x') {
2746 memmove(number + 2, number,
2747 strlen(number) + 1);
2748 number[0] = '0';
2749 number[1] = 'x';
2750 len += 2;
2751 }
2752
Victor Stinner4a587072013-11-19 12:54:53 +01002753 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002754 return NULL;
2755 break;
2756 }
2757
2758 case 's':
2759 {
2760 /* UTF-8 */
2761 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002762 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002763 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002764 break;
2765 }
2766
2767 case 'U':
2768 {
2769 PyObject *obj = va_arg(*vargs, PyObject *);
2770 assert(obj && _PyUnicode_CHECK(obj));
2771
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 break;
2775 }
2776
2777 case 'V':
2778 {
2779 PyObject *obj = va_arg(*vargs, PyObject *);
2780 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002781 if (obj) {
2782 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002783 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002784 return NULL;
2785 }
2786 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002787 assert(str != NULL);
2788 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002789 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002790 }
2791 break;
2792 }
2793
2794 case 'S':
2795 {
2796 PyObject *obj = va_arg(*vargs, PyObject *);
2797 PyObject *str;
2798 assert(obj);
2799 str = PyObject_Str(obj);
2800 if (!str)
2801 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002802 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002803 Py_DECREF(str);
2804 return NULL;
2805 }
2806 Py_DECREF(str);
2807 break;
2808 }
2809
2810 case 'R':
2811 {
2812 PyObject *obj = va_arg(*vargs, PyObject *);
2813 PyObject *repr;
2814 assert(obj);
2815 repr = PyObject_Repr(obj);
2816 if (!repr)
2817 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002818 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002819 Py_DECREF(repr);
2820 return NULL;
2821 }
2822 Py_DECREF(repr);
2823 break;
2824 }
2825
2826 case 'A':
2827 {
2828 PyObject *obj = va_arg(*vargs, PyObject *);
2829 PyObject *ascii;
2830 assert(obj);
2831 ascii = PyObject_ASCII(obj);
2832 if (!ascii)
2833 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002834 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002835 Py_DECREF(ascii);
2836 return NULL;
2837 }
2838 Py_DECREF(ascii);
2839 break;
2840 }
2841
2842 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002843 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002844 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002845 break;
2846
2847 default:
2848 /* if we stumble upon an unknown formatting code, copy the rest
2849 of the format string to the output string. (we cannot just
2850 skip the code, since there's no way to know what's in the
2851 argument list) */
2852 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002853 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002854 return NULL;
2855 f = p+len;
2856 return f;
2857 }
2858
2859 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002860 return f;
2861}
2862
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863PyObject *
2864PyUnicode_FromFormatV(const char *format, va_list vargs)
2865{
Victor Stinnere215d962012-10-06 23:03:36 +02002866 va_list vargs2;
2867 const char *f;
2868 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002869
Victor Stinner8f674cc2013-04-17 23:02:17 +02002870 _PyUnicodeWriter_Init(&writer);
2871 writer.min_length = strlen(format) + 100;
2872 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002873
Benjamin Peterson0c212142016-09-20 20:39:33 -07002874 // Copy varags to be able to pass a reference to a subfunction.
2875 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002876
2877 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002878 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002879 f = unicode_fromformat_arg(&writer, f, &vargs2);
2880 if (f == NULL)
2881 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002884 const char *p;
2885 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002886
Victor Stinnere215d962012-10-06 23:03:36 +02002887 p = f;
2888 do
2889 {
2890 if ((unsigned char)*p > 127) {
2891 PyErr_Format(PyExc_ValueError,
2892 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2893 "string, got a non-ASCII byte: 0x%02x",
2894 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002895 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002896 }
2897 p++;
2898 }
2899 while (*p != '\0' && *p != '%');
2900 len = p - f;
2901
2902 if (*p == '\0')
2903 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002904
2905 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002906 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002907
2908 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002910 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002911 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002912 return _PyUnicodeWriter_Finish(&writer);
2913
2914 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002915 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002916 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918}
2919
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920PyObject *
2921PyUnicode_FromFormat(const char *format, ...)
2922{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002923 PyObject* ret;
2924 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
2926#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002927 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 ret = PyUnicode_FromFormatV(format, vargs);
2932 va_end(vargs);
2933 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002934}
2935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936#ifdef HAVE_WCHAR_H
2937
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002938/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939
Victor Stinnerd88d9832011-09-06 02:00:05 +02002940 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941 character) required to convert the unicode object. Ignore size argument.
2942
Victor Stinnerd88d9832011-09-06 02:00:05 +02002943 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002944 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002946Py_ssize_t
2947PyUnicode_AsWideChar(PyObject *unicode,
2948 wchar_t *w,
2949 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00002950{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002951 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 const wchar_t *wstr;
2953
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002954 if (unicode == NULL) {
2955 PyErr_BadInternalCall();
2956 return -1;
2957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
Victor Stinner137c34c2010-09-29 10:25:54 +00002974wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002975PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 Py_ssize_t *size)
2977{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002978 const wchar_t *wstr;
2979 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 Py_ssize_t buflen;
2981
2982 if (unicode == NULL) {
2983 PyErr_BadInternalCall();
2984 return NULL;
2985 }
2986
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002987 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
2988 if (wstr == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002989 return NULL;
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002990 }
2991 if (size == NULL && wcslen(wstr) != (size_t)buflen) {
2992 PyErr_SetString(PyExc_ValueError,
2993 "embedded null character");
2994 return NULL;
2995 }
2996
2997 buffer = PyMem_NEW(wchar_t, buflen + 1);
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 if (buffer == NULL) {
2999 PyErr_NoMemory();
3000 return NULL;
3001 }
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003002 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003003 if (size != NULL)
3004 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003005 return buffer;
3006}
3007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003008#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003012{
Victor Stinner8faf8212011-12-08 22:14:11 +01003013 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 PyErr_SetString(PyExc_ValueError,
3015 "chr() arg not in range(0x110000)");
3016 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003017 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003018
Victor Stinner985a82a2014-01-03 12:53:47 +01003019 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020}
3021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003023PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003027 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003028 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003029 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 Py_INCREF(obj);
3031 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 }
3033 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 /* For a Unicode subtype that's not a Unicode object,
3035 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003036 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003038 PyErr_Format(PyExc_TypeError,
3039 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003040 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003041 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042}
3043
Alexander Belopolsky40018472011-02-26 01:02:56 +00003044PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003045PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003046 const char *encoding,
3047 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003049 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003051
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 PyErr_BadInternalCall();
3054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 /* Decoding bytes objects is the most common case and should be fast */
3058 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003059 if (PyBytes_GET_SIZE(obj) == 0)
3060 _Py_RETURN_UNICODE_EMPTY();
3061 v = PyUnicode_Decode(
3062 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3063 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 return v;
3065 }
3066
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003067 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 PyErr_SetString(PyExc_TypeError,
3069 "decoding str is not supported");
3070 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003071 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003073 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3074 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3075 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003076 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003077 Py_TYPE(obj)->tp_name);
3078 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003079 }
Tim Petersced69f82003-09-16 20:30:58 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003082 PyBuffer_Release(&buffer);
3083 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003085
Serhiy Storchaka05997252013-01-26 12:14:02 +02003086 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003088 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089}
3090
Victor Stinnerebe17e02016-10-12 13:57:45 +02003091/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3092 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3093 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003094int
3095_Py_normalize_encoding(const char *encoding,
3096 char *lower,
3097 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003099 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003100 char *l;
3101 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003102 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003103
Victor Stinner942889a2016-09-05 15:40:10 -07003104 assert(encoding != NULL);
3105
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003106 e = encoding;
3107 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003109 punct = 0;
3110 while (1) {
3111 char c = *e;
3112 if (c == 0) {
3113 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 }
Victor Stinner942889a2016-09-05 15:40:10 -07003115
3116 if (Py_ISALNUM(c) || c == '.') {
3117 if (punct && l != lower) {
3118 if (l == l_end) {
3119 return 0;
3120 }
3121 *l++ = '_';
3122 }
3123 punct = 0;
3124
3125 if (l == l_end) {
3126 return 0;
3127 }
3128 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003129 }
3130 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003131 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003132 }
Victor Stinner942889a2016-09-05 15:40:10 -07003133
3134 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003137 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003138}
3139
Alexander Belopolsky40018472011-02-26 01:02:56 +00003140PyObject *
3141PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003142 Py_ssize_t size,
3143 const char *encoding,
3144 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003145{
3146 PyObject *buffer = NULL, *unicode;
3147 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003148 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3149
3150 if (encoding == NULL) {
3151 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3152 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003153
Fred Drakee4315f52000-05-09 19:53:39 +00003154 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003155 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3156 char *lower = buflower;
3157
3158 /* Fast paths */
3159 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3160 lower += 3;
3161 if (*lower == '_') {
3162 /* Match "utf8" and "utf_8" */
3163 lower++;
3164 }
3165
3166 if (lower[0] == '8' && lower[1] == 0) {
3167 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3168 }
3169 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3170 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3171 }
3172 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3173 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3174 }
3175 }
3176 else {
3177 if (strcmp(lower, "ascii") == 0
3178 || strcmp(lower, "us_ascii") == 0) {
3179 return PyUnicode_DecodeASCII(s, size, errors);
3180 }
Steve Dowercc16be82016-09-08 10:35:16 -07003181 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003182 else if (strcmp(lower, "mbcs") == 0) {
3183 return PyUnicode_DecodeMBCS(s, size, errors);
3184 }
3185 #endif
3186 else if (strcmp(lower, "latin1") == 0
3187 || strcmp(lower, "latin_1") == 0
3188 || strcmp(lower, "iso_8859_1") == 0
3189 || strcmp(lower, "iso8859_1") == 0) {
3190 return PyUnicode_DecodeLatin1(s, size, errors);
3191 }
3192 }
Victor Stinner37296e82010-06-10 13:36:23 +00003193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003194
3195 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003196 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003197 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003198 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003199 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200 if (buffer == NULL)
3201 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003202 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 if (unicode == NULL)
3204 goto onError;
3205 if (!PyUnicode_Check(unicode)) {
3206 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003207 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3208 "use codecs.decode() to decode to arbitrary types",
3209 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003210 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 Py_DECREF(unicode);
3212 goto onError;
3213 }
3214 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003215 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003216
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 Py_XDECREF(buffer);
3219 return NULL;
3220}
3221
Alexander Belopolsky40018472011-02-26 01:02:56 +00003222PyObject *
3223PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003224 const char *encoding,
3225 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003226{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003229 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003230 }
3231
Serhiy Storchaka00939072016-10-27 21:05:49 +03003232 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3233 "PyUnicode_AsDecodedObject() is deprecated; "
3234 "use PyCodec_Decode() to decode from str", 1) < 0)
3235 return NULL;
3236
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003237 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003239
3240 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003241 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242}
3243
Alexander Belopolsky40018472011-02-26 01:02:56 +00003244PyObject *
3245PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003246 const char *encoding,
3247 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003248{
3249 PyObject *v;
3250
3251 if (!PyUnicode_Check(unicode)) {
3252 PyErr_BadArgument();
3253 goto onError;
3254 }
3255
Serhiy Storchaka00939072016-10-27 21:05:49 +03003256 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3257 "PyUnicode_AsDecodedUnicode() is deprecated; "
3258 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3259 return NULL;
3260
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003261 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003262 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003263
3264 /* Decode via the codec registry */
3265 v = PyCodec_Decode(unicode, encoding, errors);
3266 if (v == NULL)
3267 goto onError;
3268 if (!PyUnicode_Check(v)) {
3269 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003270 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3271 "use codecs.decode() to decode to arbitrary types",
3272 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003273 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003274 Py_DECREF(v);
3275 goto onError;
3276 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003277 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003280 return NULL;
3281}
3282
Alexander Belopolsky40018472011-02-26 01:02:56 +00003283PyObject *
3284PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003285 Py_ssize_t size,
3286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003290
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003291 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3295 Py_DECREF(unicode);
3296 return v;
3297}
3298
Alexander Belopolsky40018472011-02-26 01:02:56 +00003299PyObject *
3300PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003301 const char *encoding,
3302 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003303{
3304 PyObject *v;
3305
3306 if (!PyUnicode_Check(unicode)) {
3307 PyErr_BadArgument();
3308 goto onError;
3309 }
3310
Serhiy Storchaka00939072016-10-27 21:05:49 +03003311 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3312 "PyUnicode_AsEncodedObject() is deprecated; "
3313 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3314 "or PyCodec_Encode() for generic encoding", 1) < 0)
3315 return NULL;
3316
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003318 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003319
3320 /* Encode via the codec registry */
3321 v = PyCodec_Encode(unicode, encoding, errors);
3322 if (v == NULL)
3323 goto onError;
3324 return v;
3325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327 return NULL;
3328}
3329
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003330static size_t
3331wcstombs_errorpos(const wchar_t *wstr)
3332{
3333 size_t len;
3334#if SIZEOF_WCHAR_T == 2
3335 wchar_t buf[3];
3336#else
3337 wchar_t buf[2];
3338#endif
3339 char outbuf[MB_LEN_MAX];
3340 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003341
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003342#if SIZEOF_WCHAR_T == 2
3343 buf[2] = 0;
3344#else
3345 buf[1] = 0;
3346#endif
3347 start = wstr;
3348 while (*wstr != L'\0')
3349 {
3350 previous = wstr;
3351#if SIZEOF_WCHAR_T == 2
3352 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3353 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3354 {
3355 buf[0] = wstr[0];
3356 buf[1] = wstr[1];
3357 wstr += 2;
3358 }
3359 else {
3360 buf[0] = *wstr;
3361 buf[1] = 0;
3362 wstr++;
3363 }
3364#else
3365 buf[0] = *wstr;
3366 wstr++;
3367#endif
3368 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003369 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 }
3372
3373 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return 0;
3375}
3376
Victor Stinner1b579672011-12-17 05:47:23 +01003377static int
3378locale_error_handler(const char *errors, int *surrogateescape)
3379{
Victor Stinner50149202015-09-22 00:26:54 +02003380 _Py_error_handler error_handler = get_error_handler(errors);
3381 switch (error_handler)
3382 {
3383 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003384 *surrogateescape = 0;
3385 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003386 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003387 *surrogateescape = 1;
3388 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003389 default:
3390 PyErr_Format(PyExc_ValueError,
3391 "only 'strict' and 'surrogateescape' error handlers "
3392 "are supported, not '%s'",
3393 errors);
3394 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003395 }
Victor Stinner1b579672011-12-17 05:47:23 +01003396}
3397
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003399PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003400{
3401 Py_ssize_t wlen, wlen2;
3402 wchar_t *wstr;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003403 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003404 PyObject *bytes, *reason, *exc;
3405 size_t error_pos, errlen;
Victor Stinner1b579672011-12-17 05:47:23 +01003406 int surrogateescape;
3407
3408 if (locale_error_handler(errors, &surrogateescape) < 0)
3409 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410
3411 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3412 if (wstr == NULL)
3413 return NULL;
3414
3415 wlen2 = wcslen(wstr);
3416 if (wlen2 != wlen) {
3417 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003418 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003419 return NULL;
3420 }
3421
3422 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003423 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424 char *str;
3425
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003426 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 if (str == NULL) {
3428 if (error_pos == (size_t)-1) {
3429 PyErr_NoMemory();
3430 PyMem_Free(wstr);
3431 return NULL;
3432 }
3433 else {
3434 goto encode_error;
3435 }
3436 }
3437 PyMem_Free(wstr);
3438
3439 bytes = PyBytes_FromString(str);
3440 PyMem_Free(str);
3441 }
3442 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003443 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003444 size_t len, len2;
3445
3446 len = wcstombs(NULL, wstr, 0);
3447 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003448 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 goto encode_error;
3450 }
3451
3452 bytes = PyBytes_FromStringAndSize(NULL, len);
3453 if (bytes == NULL) {
3454 PyMem_Free(wstr);
3455 return NULL;
3456 }
3457
3458 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3459 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003460 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003461 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003462 goto encode_error;
3463 }
3464 PyMem_Free(wstr);
3465 }
3466 return bytes;
3467
3468encode_error:
3469 errmsg = strerror(errno);
3470 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003471
3472 if (error_pos == (size_t)-1)
3473 error_pos = wcstombs_errorpos(wstr);
3474
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003475 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003476
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003477 wstr = Py_DecodeLocale(errmsg, &errlen);
3478 if (wstr != NULL) {
3479 reason = PyUnicode_FromWideChar(wstr, errlen);
3480 PyMem_RawFree(wstr);
3481 } else {
3482 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003483 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003484
Victor Stinner2f197072011-12-17 07:08:30 +01003485 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003486 reason = PyUnicode_FromString(
3487 "wcstombs() encountered an unencodable "
3488 "wide character");
3489 if (reason == NULL)
3490 return NULL;
3491
3492 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3493 "locale", unicode,
3494 (Py_ssize_t)error_pos,
3495 (Py_ssize_t)(error_pos+1),
3496 reason);
3497 Py_DECREF(reason);
3498 if (exc != NULL) {
3499 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003500 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003501 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003502 return NULL;
3503}
3504
Victor Stinnerad158722010-10-27 00:25:46 +00003505PyObject *
3506PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003507{
Steve Dowercc16be82016-09-08 10:35:16 -07003508#if defined(__APPLE__)
3509 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003510#else
Victor Stinner793b5312011-04-27 00:24:21 +02003511 PyInterpreterState *interp = PyThreadState_GET()->interp;
3512 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3513 cannot use it to encode and decode filenames before it is loaded. Load
3514 the Python codec requires to encode at least its own filename. Use the C
3515 version of the locale codec until the codec registry is initialized and
3516 the Python codec is loaded.
3517
3518 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3519 cannot only rely on it: check also interp->fscodec_initialized for
3520 subinterpreters. */
3521 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003522 return PyUnicode_AsEncodedString(unicode,
3523 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003524 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003525 }
3526 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003527 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003528 }
Victor Stinnerad158722010-10-27 00:25:46 +00003529#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003530}
3531
Alexander Belopolsky40018472011-02-26 01:02:56 +00003532PyObject *
3533PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003534 const char *encoding,
3535 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003536{
3537 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003538 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003539
Guido van Rossumd57fd912000-03-10 22:53:23 +00003540 if (!PyUnicode_Check(unicode)) {
3541 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543 }
Fred Drakee4315f52000-05-09 19:53:39 +00003544
Victor Stinner942889a2016-09-05 15:40:10 -07003545 if (encoding == NULL) {
3546 return _PyUnicode_AsUTF8String(unicode, errors);
3547 }
3548
Fred Drakee4315f52000-05-09 19:53:39 +00003549 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003550 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3551 char *lower = buflower;
3552
3553 /* Fast paths */
3554 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3555 lower += 3;
3556 if (*lower == '_') {
3557 /* Match "utf8" and "utf_8" */
3558 lower++;
3559 }
3560
3561 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003562 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003563 }
3564 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3565 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3566 }
3567 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3568 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3569 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003570 }
Victor Stinner942889a2016-09-05 15:40:10 -07003571 else {
3572 if (strcmp(lower, "ascii") == 0
3573 || strcmp(lower, "us_ascii") == 0) {
3574 return _PyUnicode_AsASCIIString(unicode, errors);
3575 }
Steve Dowercc16be82016-09-08 10:35:16 -07003576#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003577 else if (strcmp(lower, "mbcs") == 0) {
3578 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3579 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003580#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003581 else if (strcmp(lower, "latin1") == 0 ||
3582 strcmp(lower, "latin_1") == 0 ||
3583 strcmp(lower, "iso_8859_1") == 0 ||
3584 strcmp(lower, "iso8859_1") == 0) {
3585 return _PyUnicode_AsLatin1String(unicode, errors);
3586 }
3587 }
Victor Stinner37296e82010-06-10 13:36:23 +00003588 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003589
3590 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003591 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003592 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003593 return NULL;
3594
3595 /* The normal path */
3596 if (PyBytes_Check(v))
3597 return v;
3598
3599 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003600 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003601 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003602 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003603
3604 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003605 "encoder %s returned bytearray instead of bytes; "
3606 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003607 encoding);
3608 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003609 Py_DECREF(v);
3610 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003611 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003612
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003613 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3614 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003615 Py_DECREF(v);
3616 return b;
3617 }
3618
3619 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003620 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3621 "use codecs.encode() to encode to arbitrary types",
3622 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003623 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003624 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003625 return NULL;
3626}
3627
Alexander Belopolsky40018472011-02-26 01:02:56 +00003628PyObject *
3629PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003630 const char *encoding,
3631 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003632{
3633 PyObject *v;
3634
3635 if (!PyUnicode_Check(unicode)) {
3636 PyErr_BadArgument();
3637 goto onError;
3638 }
3639
Serhiy Storchaka00939072016-10-27 21:05:49 +03003640 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3641 "PyUnicode_AsEncodedUnicode() is deprecated; "
3642 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3643 return NULL;
3644
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003645 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003647
3648 /* Encode via the codec registry */
3649 v = PyCodec_Encode(unicode, encoding, errors);
3650 if (v == NULL)
3651 goto onError;
3652 if (!PyUnicode_Check(v)) {
3653 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003654 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3655 "use codecs.encode() to encode to arbitrary types",
3656 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003657 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003658 Py_DECREF(v);
3659 goto onError;
3660 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003662
Benjamin Peterson29060642009-01-31 22:14:21 +00003663 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664 return NULL;
3665}
3666
Victor Stinner2f197072011-12-17 07:08:30 +01003667static size_t
3668mbstowcs_errorpos(const char *str, size_t len)
3669{
3670#ifdef HAVE_MBRTOWC
3671 const char *start = str;
3672 mbstate_t mbs;
3673 size_t converted;
3674 wchar_t ch;
3675
3676 memset(&mbs, 0, sizeof mbs);
3677 while (len)
3678 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003679 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003680 if (converted == 0)
3681 /* Reached end of string */
3682 break;
3683 if (converted == (size_t)-1 || converted == (size_t)-2) {
3684 /* Conversion error or incomplete character */
3685 return str - start;
3686 }
3687 else {
3688 str += converted;
3689 len -= converted;
3690 }
3691 }
3692 /* failed to find the undecodable byte sequence */
3693 return 0;
3694#endif
3695 return 0;
3696}
3697
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003698PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003699PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003700 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003701{
3702 wchar_t smallbuf[256];
3703 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3704 wchar_t *wstr;
3705 size_t wlen, wlen2;
3706 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003707 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003708 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003709 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003710 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003711
3712 if (locale_error_handler(errors, &surrogateescape) < 0)
3713 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003714
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003715 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3716 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003717 return NULL;
3718 }
3719
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003720 if (surrogateescape) {
3721 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003722 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003723 if (wstr == NULL) {
3724 if (wlen == (size_t)-1)
3725 PyErr_NoMemory();
3726 else
3727 PyErr_SetFromErrno(PyExc_OSError);
3728 return NULL;
3729 }
3730
3731 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003732 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003733 }
3734 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003735 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003736#ifndef HAVE_BROKEN_MBSTOWCS
3737 wlen = mbstowcs(NULL, str, 0);
3738#else
3739 wlen = len;
3740#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003741 if (wlen == (size_t)-1)
3742 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003743 if (wlen+1 <= smallbuf_len) {
3744 wstr = smallbuf;
3745 }
3746 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003747 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003748 if (!wstr)
3749 return PyErr_NoMemory();
3750 }
3751
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003752 wlen2 = mbstowcs(wstr, str, wlen+1);
3753 if (wlen2 == (size_t)-1) {
3754 if (wstr != smallbuf)
3755 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003756 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003757 }
3758#ifdef HAVE_BROKEN_MBSTOWCS
3759 assert(wlen2 == wlen);
3760#endif
3761 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3762 if (wstr != smallbuf)
3763 PyMem_Free(wstr);
3764 }
3765 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003766
3767decode_error:
3768 errmsg = strerror(errno);
3769 assert(errmsg != NULL);
3770
3771 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003772 wstr = Py_DecodeLocale(errmsg, &errlen);
3773 if (wstr != NULL) {
3774 reason = PyUnicode_FromWideChar(wstr, errlen);
3775 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003776 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003777
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003778 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003779 reason = PyUnicode_FromString(
3780 "mbstowcs() encountered an invalid multibyte sequence");
3781 if (reason == NULL)
3782 return NULL;
3783
3784 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3785 "locale", str, len,
3786 (Py_ssize_t)error_pos,
3787 (Py_ssize_t)(error_pos+1),
3788 reason);
3789 Py_DECREF(reason);
3790 if (exc != NULL) {
3791 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003792 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003793 }
3794 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003795}
3796
3797PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003798PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003799{
3800 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003801 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003802}
3803
3804
3805PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003806PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003807 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003808 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3809}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003810
Christian Heimes5894ba72007-11-04 11:43:14 +00003811PyObject*
3812PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3813{
Steve Dowercc16be82016-09-08 10:35:16 -07003814#if defined(__APPLE__)
3815 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003816#else
Victor Stinner793b5312011-04-27 00:24:21 +02003817 PyInterpreterState *interp = PyThreadState_GET()->interp;
3818 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3819 cannot use it to encode and decode filenames before it is loaded. Load
3820 the Python codec requires to encode at least its own filename. Use the C
3821 version of the locale codec until the codec registry is initialized and
3822 the Python codec is loaded.
3823
3824 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3825 cannot only rely on it: check also interp->fscodec_initialized for
3826 subinterpreters. */
3827 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003828 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003829 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003830 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003831 }
3832 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003833 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003834 }
Victor Stinnerad158722010-10-27 00:25:46 +00003835#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003836}
3837
Martin v. Löwis011e8422009-05-05 04:43:17 +00003838
3839int
3840PyUnicode_FSConverter(PyObject* arg, void* addr)
3841{
Brett Cannonec6ce872016-09-06 15:50:29 -07003842 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003843 PyObject *output = NULL;
3844 Py_ssize_t size;
3845 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003846 if (arg == NULL) {
3847 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003848 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003849 return 1;
3850 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003851 path = PyOS_FSPath(arg);
3852 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003853 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003854 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003855 if (PyBytes_Check(path)) {
3856 output = path;
3857 }
3858 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3859 output = PyUnicode_EncodeFSDefault(path);
3860 Py_DECREF(path);
3861 if (!output) {
3862 return 0;
3863 }
3864 assert(PyBytes_Check(output));
3865 }
3866
Victor Stinner0ea2a462010-04-30 00:22:08 +00003867 size = PyBytes_GET_SIZE(output);
3868 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003869 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003870 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003871 Py_DECREF(output);
3872 return 0;
3873 }
3874 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003875 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003876}
3877
3878
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003879int
3880PyUnicode_FSDecoder(PyObject* arg, void* addr)
3881{
Brett Cannona5711202016-09-06 19:36:01 -07003882 int is_buffer = 0;
3883 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003884 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003885 if (arg == NULL) {
3886 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003887 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003888 return 1;
3889 }
Brett Cannona5711202016-09-06 19:36:01 -07003890
3891 is_buffer = PyObject_CheckBuffer(arg);
3892 if (!is_buffer) {
3893 path = PyOS_FSPath(arg);
3894 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003895 return 0;
3896 }
Brett Cannona5711202016-09-06 19:36:01 -07003897 }
3898 else {
3899 path = arg;
3900 Py_INCREF(arg);
3901 }
3902
3903 if (PyUnicode_Check(path)) {
3904 if (PyUnicode_READY(path) == -1) {
3905 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003906 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003907 }
3908 output = path;
3909 }
3910 else if (PyBytes_Check(path) || is_buffer) {
3911 PyObject *path_bytes = NULL;
3912
3913 if (!PyBytes_Check(path) &&
3914 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3915 "path should be string, bytes, or os.PathLike, not %.200s",
3916 Py_TYPE(arg)->tp_name)) {
3917 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003918 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003919 }
3920 path_bytes = PyBytes_FromObject(path);
3921 Py_DECREF(path);
3922 if (!path_bytes) {
3923 return 0;
3924 }
3925 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3926 PyBytes_GET_SIZE(path_bytes));
3927 Py_DECREF(path_bytes);
3928 if (!output) {
3929 return 0;
3930 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003931 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003932 else {
3933 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003934 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003935 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003936 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003937 return 0;
3938 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003939 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003940 Py_DECREF(output);
3941 return 0;
3942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003944 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003945 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003946 Py_DECREF(output);
3947 return 0;
3948 }
3949 *(PyObject**)addr = output;
3950 return Py_CLEANUP_SUPPORTED;
3951}
3952
3953
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003954const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003956{
Christian Heimesf3863112007-11-22 07:46:41 +00003957 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003959 if (!PyUnicode_Check(unicode)) {
3960 PyErr_BadArgument();
3961 return NULL;
3962 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003963 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003964 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003965
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003966 if (PyUnicode_UTF8(unicode) == NULL) {
3967 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003968 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969 if (bytes == NULL)
3970 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003971 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3972 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003973 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 Py_DECREF(bytes);
3975 return NULL;
3976 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003977 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003978 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003979 PyBytes_AS_STRING(bytes),
3980 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 Py_DECREF(bytes);
3982 }
3983
3984 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003985 *psize = PyUnicode_UTF8_LENGTH(unicode);
3986 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003987}
3988
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003989const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003991{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3993}
3994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995Py_UNICODE *
3996PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 const unsigned char *one_byte;
3999#if SIZEOF_WCHAR_T == 4
4000 const Py_UCS2 *two_bytes;
4001#else
4002 const Py_UCS4 *four_bytes;
4003 const Py_UCS4 *ucs4_end;
4004 Py_ssize_t num_surrogates;
4005#endif
4006 wchar_t *w;
4007 wchar_t *wchar_end;
4008
4009 if (!PyUnicode_Check(unicode)) {
4010 PyErr_BadArgument();
4011 return NULL;
4012 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004013 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004014 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004015 assert(_PyUnicode_KIND(unicode) != 0);
4016 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004017
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004018 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004020 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4021 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022 num_surrogates = 0;
4023
4024 for (; four_bytes < ucs4_end; ++four_bytes) {
4025 if (*four_bytes > 0xFFFF)
4026 ++num_surrogates;
4027 }
4028
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004029 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4030 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4031 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032 PyErr_NoMemory();
4033 return NULL;
4034 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004035 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004037 w = _PyUnicode_WSTR(unicode);
4038 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4039 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4041 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004042 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004044 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4045 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 }
4047 else
4048 *w = *four_bytes;
4049
4050 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07004051 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052 }
4053 }
4054 *w = 0;
4055#else
4056 /* sizeof(wchar_t) == 4 */
4057 Py_FatalError("Impossible unicode object state, wstr and str "
4058 "should share memory already.");
4059 return NULL;
4060#endif
4061 }
4062 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004063 if ((size_t)_PyUnicode_LENGTH(unicode) >
4064 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4065 PyErr_NoMemory();
4066 return NULL;
4067 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004068 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4069 (_PyUnicode_LENGTH(unicode) + 1));
4070 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004071 PyErr_NoMemory();
4072 return NULL;
4073 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004074 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4075 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4076 w = _PyUnicode_WSTR(unicode);
4077 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004078
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004079 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4080 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004081 for (; w < wchar_end; ++one_byte, ++w)
4082 *w = *one_byte;
4083 /* null-terminate the wstr */
4084 *w = 0;
4085 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004086 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004088 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004089 for (; w < wchar_end; ++two_bytes, ++w)
4090 *w = *two_bytes;
4091 /* null-terminate the wstr */
4092 *w = 0;
4093#else
4094 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004095 PyObject_FREE(_PyUnicode_WSTR(unicode));
4096 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097 Py_FatalError("Impossible unicode object state, wstr "
4098 "and str should share memory already.");
4099 return NULL;
4100#endif
4101 }
4102 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07004103 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004104 }
4105 }
4106 }
4107 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004108 *size = PyUnicode_WSTR_LENGTH(unicode);
4109 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004110}
4111
Alexander Belopolsky40018472011-02-26 01:02:56 +00004112Py_UNICODE *
4113PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004114{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004115 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004116}
4117
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004118const Py_UNICODE *
4119_PyUnicode_AsUnicode(PyObject *unicode)
4120{
4121 Py_ssize_t size;
4122 const Py_UNICODE *wstr;
4123
4124 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4125 if (wstr && wcslen(wstr) != (size_t)size) {
4126 PyErr_SetString(PyExc_ValueError, "embedded null character");
4127 return NULL;
4128 }
4129 return wstr;
4130}
4131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004132
Alexander Belopolsky40018472011-02-26 01:02:56 +00004133Py_ssize_t
4134PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135{
4136 if (!PyUnicode_Check(unicode)) {
4137 PyErr_BadArgument();
4138 goto onError;
4139 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004140 if (_PyUnicode_WSTR(unicode) == NULL) {
4141 if (PyUnicode_AsUnicode(unicode) == NULL)
4142 goto onError;
4143 }
4144 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145
Benjamin Peterson29060642009-01-31 22:14:21 +00004146 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004147 return -1;
4148}
4149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004150Py_ssize_t
4151PyUnicode_GetLength(PyObject *unicode)
4152{
Victor Stinner07621332012-06-16 04:53:46 +02004153 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004154 PyErr_BadArgument();
4155 return -1;
4156 }
Victor Stinner07621332012-06-16 04:53:46 +02004157 if (PyUnicode_READY(unicode) == -1)
4158 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004159 return PyUnicode_GET_LENGTH(unicode);
4160}
4161
4162Py_UCS4
4163PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4164{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004165 void *data;
4166 int kind;
4167
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004168 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004169 PyErr_BadArgument();
4170 return (Py_UCS4)-1;
4171 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004172 if (PyUnicode_READY(unicode) == -1) {
4173 return (Py_UCS4)-1;
4174 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004175 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004176 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177 return (Py_UCS4)-1;
4178 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004179 data = PyUnicode_DATA(unicode);
4180 kind = PyUnicode_KIND(unicode);
4181 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004182}
4183
4184int
4185PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4186{
4187 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004188 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004189 return -1;
4190 }
Victor Stinner488fa492011-12-12 00:01:39 +01004191 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004192 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004193 PyErr_SetString(PyExc_IndexError, "string index out of range");
4194 return -1;
4195 }
Victor Stinner488fa492011-12-12 00:01:39 +01004196 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004197 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004198 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4199 PyErr_SetString(PyExc_ValueError, "character out of range");
4200 return -1;
4201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4203 index, ch);
4204 return 0;
4205}
4206
Alexander Belopolsky40018472011-02-26 01:02:56 +00004207const char *
4208PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004209{
Victor Stinner42cb4622010-09-01 19:39:01 +00004210 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004211}
4212
Victor Stinner554f3f02010-06-16 23:33:54 +00004213/* create or adjust a UnicodeDecodeError */
4214static void
4215make_decode_exception(PyObject **exceptionObject,
4216 const char *encoding,
4217 const char *input, Py_ssize_t length,
4218 Py_ssize_t startpos, Py_ssize_t endpos,
4219 const char *reason)
4220{
4221 if (*exceptionObject == NULL) {
4222 *exceptionObject = PyUnicodeDecodeError_Create(
4223 encoding, input, length, startpos, endpos, reason);
4224 }
4225 else {
4226 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4227 goto onError;
4228 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4229 goto onError;
4230 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4231 goto onError;
4232 }
4233 return;
4234
4235onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004236 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004237}
4238
Steve Dowercc16be82016-09-08 10:35:16 -07004239#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004240/* error handling callback helper:
4241 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004242 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004243 and adjust various state variables.
4244 return 0 on success, -1 on error
4245*/
4246
Alexander Belopolsky40018472011-02-26 01:02:56 +00004247static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004248unicode_decode_call_errorhandler_wchar(
4249 const char *errors, PyObject **errorHandler,
4250 const char *encoding, const char *reason,
4251 const char **input, const char **inend, Py_ssize_t *startinpos,
4252 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4253 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004254{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004255 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004256
4257 PyObject *restuple = NULL;
4258 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004259 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004260 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004261 Py_ssize_t requiredsize;
4262 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004263 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004264 wchar_t *repwstr;
4265 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004267 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4268 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 *errorHandler = PyCodec_LookupError(errors);
4272 if (*errorHandler == NULL)
4273 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004274 }
4275
Victor Stinner554f3f02010-06-16 23:33:54 +00004276 make_decode_exception(exceptionObject,
4277 encoding,
4278 *input, *inend - *input,
4279 *startinpos, *endinpos,
4280 reason);
4281 if (*exceptionObject == NULL)
4282 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004283
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004284 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004286 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004287 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004288 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004289 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004290 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004291 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004292 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004293
4294 /* Copy back the bytes variables, which might have been modified by the
4295 callback */
4296 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4297 if (!inputobj)
4298 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004299 *input = PyBytes_AS_STRING(inputobj);
4300 insize = PyBytes_GET_SIZE(inputobj);
4301 *inend = *input + insize;
4302 /* we can DECREF safely, as the exception has another reference,
4303 so the object won't go away. */
4304 Py_DECREF(inputobj);
4305
4306 if (newpos<0)
4307 newpos = insize+newpos;
4308 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004309 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004310 goto onError;
4311 }
4312
4313 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4314 if (repwstr == NULL)
4315 goto onError;
4316 /* need more space? (at least enough for what we
4317 have+the replacement+the rest of the string (starting
4318 at the new input position), so we won't have to check space
4319 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004320 requiredsize = *outpos;
4321 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4322 goto overflow;
4323 requiredsize += repwlen;
4324 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4325 goto overflow;
4326 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004327 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004328 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004329 requiredsize = 2*outsize;
4330 if (unicode_resize(output, requiredsize) < 0)
4331 goto onError;
4332 }
4333 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4334 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004335 *endinpos = newpos;
4336 *inptr = *input + newpos;
4337
4338 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004339 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004340 return 0;
4341
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004342 overflow:
4343 PyErr_SetString(PyExc_OverflowError,
4344 "decoded result is too long for a Python string");
4345
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004346 onError:
4347 Py_XDECREF(restuple);
4348 return -1;
4349}
Steve Dowercc16be82016-09-08 10:35:16 -07004350#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004351
4352static int
4353unicode_decode_call_errorhandler_writer(
4354 const char *errors, PyObject **errorHandler,
4355 const char *encoding, const char *reason,
4356 const char **input, const char **inend, Py_ssize_t *startinpos,
4357 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4358 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4359{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004360 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004361
4362 PyObject *restuple = NULL;
4363 PyObject *repunicode = NULL;
4364 Py_ssize_t insize;
4365 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004366 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004367 PyObject *inputobj = NULL;
4368
4369 if (*errorHandler == NULL) {
4370 *errorHandler = PyCodec_LookupError(errors);
4371 if (*errorHandler == NULL)
4372 goto onError;
4373 }
4374
4375 make_decode_exception(exceptionObject,
4376 encoding,
4377 *input, *inend - *input,
4378 *startinpos, *endinpos,
4379 reason);
4380 if (*exceptionObject == NULL)
4381 goto onError;
4382
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004383 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004384 if (restuple == NULL)
4385 goto onError;
4386 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004387 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388 goto onError;
4389 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004390 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004391 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004392
4393 /* Copy back the bytes variables, which might have been modified by the
4394 callback */
4395 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4396 if (!inputobj)
4397 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004398 *input = PyBytes_AS_STRING(inputobj);
4399 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004400 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004401 /* we can DECREF safely, as the exception has another reference,
4402 so the object won't go away. */
4403 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004406 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004407 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004408 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004409 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004410 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411
Victor Stinner170ca6f2013-04-18 00:25:28 +02004412 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004413 if (replen > 1) {
4414 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004415 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004416 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4417 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4418 goto onError;
4419 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004421 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004422
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004423 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004424 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004426 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004427 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004428 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004429
Benjamin Peterson29060642009-01-31 22:14:21 +00004430 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004433}
4434
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004435/* --- UTF-7 Codec -------------------------------------------------------- */
4436
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437/* See RFC2152 for details. We encode conservatively and decode liberally. */
4438
4439/* Three simple macros defining base-64. */
4440
4441/* Is c a base-64 character? */
4442
4443#define IS_BASE64(c) \
4444 (((c) >= 'A' && (c) <= 'Z') || \
4445 ((c) >= 'a' && (c) <= 'z') || \
4446 ((c) >= '0' && (c) <= '9') || \
4447 (c) == '+' || (c) == '/')
4448
4449/* given that c is a base-64 character, what is its base-64 value? */
4450
4451#define FROM_BASE64(c) \
4452 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4453 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4454 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4455 (c) == '+' ? 62 : 63)
4456
4457/* What is the base-64 character of the bottom 6 bits of n? */
4458
4459#define TO_BASE64(n) \
4460 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4461
4462/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4463 * decoded as itself. We are permissive on decoding; the only ASCII
4464 * byte not decoding to itself is the + which begins a base64
4465 * string. */
4466
4467#define DECODE_DIRECT(c) \
4468 ((c) <= 127 && (c) != '+')
4469
4470/* The UTF-7 encoder treats ASCII characters differently according to
4471 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4472 * the above). See RFC2152. This array identifies these different
4473 * sets:
4474 * 0 : "Set D"
4475 * alphanumeric and '(),-./:?
4476 * 1 : "Set O"
4477 * !"#$%&*;<=>@[]^_`{|}
4478 * 2 : "whitespace"
4479 * ht nl cr sp
4480 * 3 : special (must be base64 encoded)
4481 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4482 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483
Tim Petersced69f82003-09-16 20:30:58 +00004484static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485char utf7_category[128] = {
4486/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4487 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4488/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4489 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4490/* sp ! " # $ % & ' ( ) * + , - . / */
4491 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4492/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4493 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4494/* @ A B C D E F G H I J K L M N O */
4495 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4496/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4497 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4498/* ` a b c d e f g h i j k l m n o */
4499 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4500/* p q r s t u v w x y z { | } ~ del */
4501 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502};
4503
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504/* ENCODE_DIRECT: this character should be encoded as itself. The
4505 * answer depends on whether we are encoding set O as itself, and also
4506 * on whether we are encoding whitespace as itself. RFC2152 makes it
4507 * clear that the answers to these questions vary between
4508 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004509
Antoine Pitrou244651a2009-05-04 18:56:13 +00004510#define ENCODE_DIRECT(c, directO, directWS) \
4511 ((c) < 128 && (c) > 0 && \
4512 ((utf7_category[(c)] == 0) || \
4513 (directWS && (utf7_category[(c)] == 2)) || \
4514 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Alexander Belopolsky40018472011-02-26 01:02:56 +00004516PyObject *
4517PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004518 Py_ssize_t size,
4519 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004521 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4522}
4523
Antoine Pitrou244651a2009-05-04 18:56:13 +00004524/* The decoder. The only state we preserve is our read position,
4525 * i.e. how many characters we have consumed. So if we end in the
4526 * middle of a shift sequence we have to back off the read position
4527 * and the output to the beginning of the sequence, otherwise we lose
4528 * all the shift state (seen bits, number of bits seen, high
4529 * surrogate). */
4530
Alexander Belopolsky40018472011-02-26 01:02:56 +00004531PyObject *
4532PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004533 Py_ssize_t size,
4534 const char *errors,
4535 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004536{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004537 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004538 Py_ssize_t startinpos;
4539 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004541 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 const char *errmsg = "";
4543 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004544 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 unsigned int base64bits = 0;
4546 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004547 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004548 PyObject *errorHandler = NULL;
4549 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004551 if (size == 0) {
4552 if (consumed)
4553 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004554 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004555 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004557 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004558 _PyUnicodeWriter_Init(&writer);
4559 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004560
4561 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562 e = s + size;
4563
4564 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004565 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004566 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004567 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004568
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 if (inShift) { /* in a base-64 section */
4570 if (IS_BASE64(ch)) { /* consume a base-64 character */
4571 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4572 base64bits += 6;
4573 s++;
4574 if (base64bits >= 16) {
4575 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004576 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 base64bits -= 16;
4578 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004579 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 if (surrogate) {
4581 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004582 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4583 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004584 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004585 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004587 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004588 }
4589 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004590 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004591 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 }
4594 }
Victor Stinner551ac952011-11-29 22:58:13 +01004595 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 /* first surrogate */
4597 surrogate = outCh;
4598 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004600 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004601 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 }
4603 }
4604 }
4605 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004607 if (base64bits > 0) { /* left-over bits */
4608 if (base64bits >= 6) {
4609 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004610 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 errmsg = "partial character in shift sequence";
4612 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 else {
4615 /* Some bits remain; they should be zero */
4616 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004617 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 errmsg = "non-zero padding bits in shift sequence";
4619 goto utf7Error;
4620 }
4621 }
4622 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004623 if (surrogate && DECODE_DIRECT(ch)) {
4624 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4625 goto onError;
4626 }
4627 surrogate = 0;
4628 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629 /* '-' is absorbed; other terminating
4630 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004631 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004632 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004633 }
4634 }
4635 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004636 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004637 s++; /* consume '+' */
4638 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004639 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004640 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004641 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004642 }
4643 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004644 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004645 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004646 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004648 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 }
4650 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004652 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004653 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004654 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004655 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004656 else {
4657 startinpos = s-starts;
4658 s++;
4659 errmsg = "unexpected special character";
4660 goto utf7Error;
4661 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004662 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004663utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004664 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004665 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004666 errors, &errorHandler,
4667 "utf7", errmsg,
4668 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004669 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004670 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004671 }
4672
Antoine Pitrou244651a2009-05-04 18:56:13 +00004673 /* end of string */
4674
4675 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4676 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004677 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004678 if (surrogate ||
4679 (base64bits >= 6) ||
4680 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004682 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004683 errors, &errorHandler,
4684 "utf7", "unterminated shift sequence",
4685 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004686 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004687 goto onError;
4688 if (s < e)
4689 goto restart;
4690 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004691 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004692
4693 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004694 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004696 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004697 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004698 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004699 writer.kind, writer.data, shiftOutStart);
4700 Py_XDECREF(errorHandler);
4701 Py_XDECREF(exc);
4702 _PyUnicodeWriter_Dealloc(&writer);
4703 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004704 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004705 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004706 }
4707 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004708 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004709 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004710 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004711
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004712 Py_XDECREF(errorHandler);
4713 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004714 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715
Benjamin Peterson29060642009-01-31 22:14:21 +00004716 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004717 Py_XDECREF(errorHandler);
4718 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004720 return NULL;
4721}
4722
4723
Alexander Belopolsky40018472011-02-26 01:02:56 +00004724PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004725_PyUnicode_EncodeUTF7(PyObject *str,
4726 int base64SetO,
4727 int base64WhiteSpace,
4728 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004729{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 int kind;
4731 void *data;
4732 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004733 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004735 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004736 unsigned int base64bits = 0;
4737 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004738 char * out;
4739 char * start;
4740
Benjamin Petersonbac79492012-01-14 13:34:47 -05004741 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004742 return NULL;
4743 kind = PyUnicode_KIND(str);
4744 data = PyUnicode_DATA(str);
4745 len = PyUnicode_GET_LENGTH(str);
4746
4747 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004748 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004749
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004750 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004751 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004752 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004753 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004754 if (v == NULL)
4755 return NULL;
4756
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004757 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004758 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004759 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004760
Antoine Pitrou244651a2009-05-04 18:56:13 +00004761 if (inShift) {
4762 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4763 /* shifting out */
4764 if (base64bits) { /* output remaining bits */
4765 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4766 base64buffer = 0;
4767 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 }
4769 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004770 /* Characters not in the BASE64 set implicitly unshift the sequence
4771 so no '-' is required, except if the character is itself a '-' */
4772 if (IS_BASE64(ch) || ch == '-') {
4773 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004774 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004775 *out++ = (char) ch;
4776 }
4777 else {
4778 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004779 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004780 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004781 else { /* not in a shift sequence */
4782 if (ch == '+') {
4783 *out++ = '+';
4784 *out++ = '-';
4785 }
4786 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4787 *out++ = (char) ch;
4788 }
4789 else {
4790 *out++ = '+';
4791 inShift = 1;
4792 goto encode_char;
4793 }
4794 }
4795 continue;
4796encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004798 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004799
Antoine Pitrou244651a2009-05-04 18:56:13 +00004800 /* code first surrogate */
4801 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004802 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004803 while (base64bits >= 6) {
4804 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4805 base64bits -= 6;
4806 }
4807 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004808 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004809 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004810 base64bits += 16;
4811 base64buffer = (base64buffer << 16) | ch;
4812 while (base64bits >= 6) {
4813 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4814 base64bits -= 6;
4815 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004816 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004817 if (base64bits)
4818 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4819 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004820 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004821 if (_PyBytes_Resize(&v, out - start) < 0)
4822 return NULL;
4823 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004824}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004825PyObject *
4826PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4827 Py_ssize_t size,
4828 int base64SetO,
4829 int base64WhiteSpace,
4830 const char *errors)
4831{
4832 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004833 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004834 if (tmp == NULL)
4835 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004836 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004837 base64WhiteSpace, errors);
4838 Py_DECREF(tmp);
4839 return result;
4840}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004841
Antoine Pitrou244651a2009-05-04 18:56:13 +00004842#undef IS_BASE64
4843#undef FROM_BASE64
4844#undef TO_BASE64
4845#undef DECODE_DIRECT
4846#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004847
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848/* --- UTF-8 Codec -------------------------------------------------------- */
4849
Alexander Belopolsky40018472011-02-26 01:02:56 +00004850PyObject *
4851PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004852 Py_ssize_t size,
4853 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004854{
Walter Dörwald69652032004-09-07 20:24:22 +00004855 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4856}
4857
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858#include "stringlib/asciilib.h"
4859#include "stringlib/codecs.h"
4860#include "stringlib/undef.h"
4861
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004862#include "stringlib/ucs1lib.h"
4863#include "stringlib/codecs.h"
4864#include "stringlib/undef.h"
4865
4866#include "stringlib/ucs2lib.h"
4867#include "stringlib/codecs.h"
4868#include "stringlib/undef.h"
4869
4870#include "stringlib/ucs4lib.h"
4871#include "stringlib/codecs.h"
4872#include "stringlib/undef.h"
4873
Antoine Pitrouab868312009-01-10 15:40:25 +00004874/* Mask to quickly check whether a C 'long' contains a
4875 non-ASCII, UTF8-encoded char. */
4876#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004877# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004878#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004879# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004880#else
4881# error C 'long' size should be either 4 or 8!
4882#endif
4883
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884static Py_ssize_t
4885ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004888 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004890 /*
4891 * Issue #17237: m68k is a bit different from most architectures in
4892 * that objects do not use "natural alignment" - for example, int and
4893 * long are only aligned at 2-byte boundaries. Therefore the assert()
4894 * won't work; also, tests have shown that skipping the "optimised
4895 * version" will even speed up m68k.
4896 */
4897#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004899 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4900 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 /* Fast path, see in STRINGLIB(utf8_decode) for
4902 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004903 /* Help allocation */
4904 const char *_p = p;
4905 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004906 while (_p < aligned_end) {
4907 unsigned long value = *(const unsigned long *) _p;
4908 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004909 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910 *((unsigned long *)q) = value;
4911 _p += SIZEOF_LONG;
4912 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004913 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004914 p = _p;
4915 while (p < end) {
4916 if ((unsigned char)*p & 0x80)
4917 break;
4918 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004919 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004921 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004923#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004924 while (p < end) {
4925 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4926 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004927 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004928 /* Help allocation */
4929 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004930 while (_p < aligned_end) {
4931 unsigned long value = *(unsigned long *) _p;
4932 if (value & ASCII_CHAR_MASK)
4933 break;
4934 _p += SIZEOF_LONG;
4935 }
4936 p = _p;
4937 if (_p == end)
4938 break;
4939 }
4940 if ((unsigned char)*p & 0x80)
4941 break;
4942 ++p;
4943 }
4944 memcpy(dest, start, p - start);
4945 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004946}
Antoine Pitrouab868312009-01-10 15:40:25 +00004947
Victor Stinner785938e2011-12-11 20:09:03 +01004948PyObject *
4949PyUnicode_DecodeUTF8Stateful(const char *s,
4950 Py_ssize_t size,
4951 const char *errors,
4952 Py_ssize_t *consumed)
4953{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004954 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004955 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004957
4958 Py_ssize_t startinpos;
4959 Py_ssize_t endinpos;
4960 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004961 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004963 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004964
4965 if (size == 0) {
4966 if (consumed)
4967 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004968 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004969 }
4970
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004971 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4972 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004973 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 *consumed = 1;
4975 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004976 }
4977
Victor Stinner8f674cc2013-04-17 23:02:17 +02004978 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004979 writer.min_length = size;
4980 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004982
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 writer.pos = ascii_decode(s, end, writer.data);
4984 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 while (s < end) {
4986 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004988
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004990 if (PyUnicode_IS_ASCII(writer.buffer))
4991 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004992 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004993 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004994 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004995 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 } else {
4997 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004998 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999 }
5000
5001 switch (ch) {
5002 case 0:
5003 if (s == end || consumed)
5004 goto End;
5005 errmsg = "unexpected end of data";
5006 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005007 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 break;
5009 case 1:
5010 errmsg = "invalid start byte";
5011 startinpos = s - starts;
5012 endinpos = startinpos + 1;
5013 break;
5014 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005015 case 3:
5016 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 errmsg = "invalid continuation byte";
5018 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005019 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005020 break;
5021 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005022 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 goto onError;
5024 continue;
5025 }
5026
Victor Stinner1d65d912015-10-05 13:43:50 +02005027 if (error_handler == _Py_ERROR_UNKNOWN)
5028 error_handler = get_error_handler(errors);
5029
5030 switch (error_handler) {
5031 case _Py_ERROR_IGNORE:
5032 s += (endinpos - startinpos);
5033 break;
5034
5035 case _Py_ERROR_REPLACE:
5036 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5037 goto onError;
5038 s += (endinpos - startinpos);
5039 break;
5040
5041 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005042 {
5043 Py_ssize_t i;
5044
Victor Stinner1d65d912015-10-05 13:43:50 +02005045 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5046 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005047 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005048 ch = (Py_UCS4)(unsigned char)(starts[i]);
5049 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5050 ch + 0xdc00);
5051 writer.pos++;
5052 }
5053 s += (endinpos - startinpos);
5054 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005055 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005056
5057 default:
5058 if (unicode_decode_call_errorhandler_writer(
5059 errors, &error_handler_obj,
5060 "utf-8", errmsg,
5061 &starts, &end, &startinpos, &endinpos, &exc, &s,
5062 &writer))
5063 goto onError;
5064 }
Victor Stinner785938e2011-12-11 20:09:03 +01005065 }
5066
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005068 if (consumed)
5069 *consumed = s - starts;
5070
Victor Stinner1d65d912015-10-05 13:43:50 +02005071 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005072 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005073 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005074
5075onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005076 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005078 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005079 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005080}
5081
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005082
Victor Stinner91106cd2017-12-13 12:29:09 +01005083/* UTF-8 decoder using the surrogateescape error handler .
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005084
Victor Stinner91106cd2017-12-13 12:29:09 +01005085 On success, return a pointer to a newly allocated wide character string (use
5086 PyMem_RawFree() to free the memory) and write the output length (in number
5087 of wchar_t units) into *p_wlen (if p_wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005088
Victor Stinner91106cd2017-12-13 12:29:09 +01005089 On memory allocation failure, return -1 and write (size_t)-1 into *p_wlen
5090 (if p_wlen is set). */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005091wchar_t*
Victor Stinner91106cd2017-12-13 12:29:09 +01005092_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size, size_t *p_wlen)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005094 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005095 wchar_t *unicode;
5096 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097
5098 /* Note: size will always be longer than the resulting Unicode
5099 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01005100 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
5101 if (p_wlen) {
5102 *p_wlen = (size_t)-1;
5103 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005104 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005105 }
5106
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005107 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01005108 if (!unicode) {
5109 if (p_wlen) {
5110 *p_wlen = (size_t)-1;
5111 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005113 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005114
5115 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005116 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005117 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005118 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005119 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005120#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005121 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005122#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005123 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005124#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005125 if (ch > 0xFF) {
5126#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005127 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005128#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005129 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005130 /* compute and append the two surrogates: */
5131 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5132 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5133#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005134 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005135 else {
5136 if (!ch && s == e)
5137 break;
5138 /* surrogateescape */
5139 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5140 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005141 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005142 unicode[outpos] = L'\0';
Victor Stinner91106cd2017-12-13 12:29:09 +01005143 if (p_wlen) {
5144 *p_wlen = outpos;
5145 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005146 return unicode;
5147}
5148
Antoine Pitrouab868312009-01-10 15:40:25 +00005149
Victor Stinnere47e6982017-12-21 15:45:16 +01005150/* UTF-8 encoder using the surrogateescape error handler .
5151
5152 On success, return a pointer to a newly allocated character string (use
5153 PyMem_Free() to free the memory).
5154
5155 On encoding failure, return NULL and write the position of the invalid
5156 surrogate character into *error_pos (if error_pos is set).
5157
5158 On memory allocation failure, return NULL and write (size_t)-1 into
5159 *error_pos (if error_pos is set). */
5160char*
5161_Py_EncodeUTF8_surrogateescape(const wchar_t *text, size_t *error_pos)
5162{
5163 const Py_ssize_t max_char_size = 4;
5164 Py_ssize_t len = wcslen(text);
5165
5166 assert(len >= 0);
5167
5168 char *bytes;
5169 if (len <= PY_SSIZE_T_MAX / max_char_size - 1) {
5170 bytes = PyMem_Malloc((len + 1) * max_char_size);
5171 }
5172 else {
5173 bytes = NULL;
5174 }
5175 if (bytes == NULL) {
5176 if (error_pos != NULL) {
5177 *error_pos = (size_t)-1;
5178 }
5179 return NULL;
5180 }
5181
5182 char *p = bytes;
5183 Py_ssize_t i;
5184 for (i = 0; i < len;) {
5185 Py_UCS4 ch = text[i++];
5186
5187 if (ch < 0x80) {
5188 /* Encode ASCII */
5189 *p++ = (char) ch;
5190
5191 }
5192 else if (ch < 0x0800) {
5193 /* Encode Latin-1 */
5194 *p++ = (char)(0xc0 | (ch >> 6));
5195 *p++ = (char)(0x80 | (ch & 0x3f));
5196 }
5197 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5198 /* surrogateescape error handler */
5199 if (!(0xDC80 <= ch && ch <= 0xDCFF)) {
5200 if (error_pos != NULL) {
5201 *error_pos = (size_t)i - 1;
5202 }
5203 goto error;
5204 }
5205 *p++ = (char)(ch & 0xff);
5206 }
5207 else if (ch < 0x10000) {
5208 *p++ = (char)(0xe0 | (ch >> 12));
5209 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5210 *p++ = (char)(0x80 | (ch & 0x3f));
5211 }
5212 else { /* ch >= 0x10000 */
5213 assert(ch <= MAX_UNICODE);
5214 /* Encode UCS4 Unicode ordinals */
5215 *p++ = (char)(0xf0 | (ch >> 18));
5216 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5217 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5218 *p++ = (char)(0x80 | (ch & 0x3f));
5219 }
5220 }
5221 *p++ = '\0';
5222
5223 size_t final_size = (p - bytes);
5224 char *bytes2 = PyMem_Realloc(bytes, final_size);
5225 if (bytes2 == NULL) {
5226 if (error_pos != NULL) {
5227 *error_pos = (size_t)-1;
5228 }
5229 goto error;
5230 }
5231 return bytes2;
5232
5233 error:
5234 PyMem_Free(bytes);
5235 return NULL;
5236}
5237
5238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005239/* Primary internal function which creates utf8 encoded bytes objects.
5240
5241 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005242 and allocate exactly as much space needed at the end. Else allocate the
5243 maximum possible needed (4 result bytes per Unicode character), and return
5244 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005245*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005246PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005247_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005248{
Victor Stinner6099a032011-12-18 14:22:26 +01005249 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005250 void *data;
5251 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005253 if (!PyUnicode_Check(unicode)) {
5254 PyErr_BadArgument();
5255 return NULL;
5256 }
5257
5258 if (PyUnicode_READY(unicode) == -1)
5259 return NULL;
5260
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005261 if (PyUnicode_UTF8(unicode))
5262 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5263 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005264
5265 kind = PyUnicode_KIND(unicode);
5266 data = PyUnicode_DATA(unicode);
5267 size = PyUnicode_GET_LENGTH(unicode);
5268
Benjamin Petersonead6b532011-12-20 17:23:42 -06005269 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005270 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005271 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005272 case PyUnicode_1BYTE_KIND:
5273 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5274 assert(!PyUnicode_IS_ASCII(unicode));
5275 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5276 case PyUnicode_2BYTE_KIND:
5277 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5278 case PyUnicode_4BYTE_KIND:
5279 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005280 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005281}
5282
Alexander Belopolsky40018472011-02-26 01:02:56 +00005283PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005284PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5285 Py_ssize_t size,
5286 const char *errors)
5287{
5288 PyObject *v, *unicode;
5289
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005290 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005291 if (unicode == NULL)
5292 return NULL;
5293 v = _PyUnicode_AsUTF8String(unicode, errors);
5294 Py_DECREF(unicode);
5295 return v;
5296}
5297
5298PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005299PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005300{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005301 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005302}
5303
Walter Dörwald41980ca2007-08-16 21:55:45 +00005304/* --- UTF-32 Codec ------------------------------------------------------- */
5305
5306PyObject *
5307PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005308 Py_ssize_t size,
5309 const char *errors,
5310 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005311{
5312 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5313}
5314
5315PyObject *
5316PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 Py_ssize_t size,
5318 const char *errors,
5319 int *byteorder,
5320 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005321{
5322 const char *starts = s;
5323 Py_ssize_t startinpos;
5324 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005325 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005326 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005327 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005328 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005329 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005330 PyObject *errorHandler = NULL;
5331 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005332
Walter Dörwald41980ca2007-08-16 21:55:45 +00005333 q = (unsigned char *)s;
5334 e = q + size;
5335
5336 if (byteorder)
5337 bo = *byteorder;
5338
5339 /* Check for BOM marks (U+FEFF) in the input and adjust current
5340 byte order setting accordingly. In native mode, the leading BOM
5341 mark is skipped, in all other modes, it is copied to the output
5342 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005343 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005344 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005345 if (bom == 0x0000FEFF) {
5346 bo = -1;
5347 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005349 else if (bom == 0xFFFE0000) {
5350 bo = 1;
5351 q += 4;
5352 }
5353 if (byteorder)
5354 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005355 }
5356
Victor Stinnere64322e2012-10-30 23:12:47 +01005357 if (q == e) {
5358 if (consumed)
5359 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005360 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005361 }
5362
Victor Stinnere64322e2012-10-30 23:12:47 +01005363#ifdef WORDS_BIGENDIAN
5364 le = bo < 0;
5365#else
5366 le = bo <= 0;
5367#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005369
Victor Stinner8f674cc2013-04-17 23:02:17 +02005370 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005371 writer.min_length = (e - q + 3) / 4;
5372 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005373 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005374
Victor Stinnere64322e2012-10-30 23:12:47 +01005375 while (1) {
5376 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005377 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005378
Victor Stinnere64322e2012-10-30 23:12:47 +01005379 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005380 enum PyUnicode_Kind kind = writer.kind;
5381 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005382 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005383 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005384 if (le) {
5385 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005386 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005387 if (ch > maxch)
5388 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005389 if (kind != PyUnicode_1BYTE_KIND &&
5390 Py_UNICODE_IS_SURROGATE(ch))
5391 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005392 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005393 q += 4;
5394 } while (q <= last);
5395 }
5396 else {
5397 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005398 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005399 if (ch > maxch)
5400 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005401 if (kind != PyUnicode_1BYTE_KIND &&
5402 Py_UNICODE_IS_SURROGATE(ch))
5403 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005404 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005405 q += 4;
5406 } while (q <= last);
5407 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005408 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005409 }
5410
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005411 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005412 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005413 startinpos = ((const char *)q) - starts;
5414 endinpos = startinpos + 4;
5415 }
5416 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005417 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005419 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005420 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005421 startinpos = ((const char *)q) - starts;
5422 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005423 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005424 else {
5425 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005426 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005427 goto onError;
5428 q += 4;
5429 continue;
5430 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005431 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005432 startinpos = ((const char *)q) - starts;
5433 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005435
5436 /* The remaining input chars are ignored if the callback
5437 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005438 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005439 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005440 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005441 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005442 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005444 }
5445
Walter Dörwald41980ca2007-08-16 21:55:45 +00005446 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005447 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005448
Walter Dörwald41980ca2007-08-16 21:55:45 +00005449 Py_XDECREF(errorHandler);
5450 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005451 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005452
Benjamin Peterson29060642009-01-31 22:14:21 +00005453 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005454 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005455 Py_XDECREF(errorHandler);
5456 Py_XDECREF(exc);
5457 return NULL;
5458}
5459
5460PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005461_PyUnicode_EncodeUTF32(PyObject *str,
5462 const char *errors,
5463 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005464{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005465 enum PyUnicode_Kind kind;
5466 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005467 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005468 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005469 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005470#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005471 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005472#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005473 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005474#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005475 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005476 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005477 PyObject *errorHandler = NULL;
5478 PyObject *exc = NULL;
5479 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005480
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005481 if (!PyUnicode_Check(str)) {
5482 PyErr_BadArgument();
5483 return NULL;
5484 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005485 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005486 return NULL;
5487 kind = PyUnicode_KIND(str);
5488 data = PyUnicode_DATA(str);
5489 len = PyUnicode_GET_LENGTH(str);
5490
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005491 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005492 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005493 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005494 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005495 if (v == NULL)
5496 return NULL;
5497
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005498 /* output buffer is 4-bytes aligned */
5499 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005500 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005501 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005502 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005503 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005504 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005505
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005506 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005507 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005508 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005509 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005510 else
5511 encoding = "utf-32";
5512
5513 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005514 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5515 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005516 }
5517
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005518 pos = 0;
5519 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005520 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005521
5522 if (kind == PyUnicode_2BYTE_KIND) {
5523 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5524 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005525 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005526 else {
5527 assert(kind == PyUnicode_4BYTE_KIND);
5528 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5529 &out, native_ordering);
5530 }
5531 if (pos == len)
5532 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005533
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005534 rep = unicode_encode_call_errorhandler(
5535 errors, &errorHandler,
5536 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005537 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005538 if (!rep)
5539 goto error;
5540
5541 if (PyBytes_Check(rep)) {
5542 repsize = PyBytes_GET_SIZE(rep);
5543 if (repsize & 3) {
5544 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005545 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005546 "surrogates not allowed");
5547 goto error;
5548 }
5549 moreunits = repsize / 4;
5550 }
5551 else {
5552 assert(PyUnicode_Check(rep));
5553 if (PyUnicode_READY(rep) < 0)
5554 goto error;
5555 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5556 if (!PyUnicode_IS_ASCII(rep)) {
5557 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005558 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005559 "surrogates not allowed");
5560 goto error;
5561 }
5562 }
5563
5564 /* four bytes are reserved for each surrogate */
5565 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005566 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005567 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005568 /* integer overflow */
5569 PyErr_NoMemory();
5570 goto error;
5571 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005572 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005573 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005574 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005575 }
5576
5577 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005578 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005579 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005580 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005581 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005582 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5583 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005584 }
5585
5586 Py_CLEAR(rep);
5587 }
5588
5589 /* Cut back to size actually needed. This is necessary for, for example,
5590 encoding of a string containing isolated surrogates and the 'ignore'
5591 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005592 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005593 if (nsize != PyBytes_GET_SIZE(v))
5594 _PyBytes_Resize(&v, nsize);
5595 Py_XDECREF(errorHandler);
5596 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005597 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005598 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005599 error:
5600 Py_XDECREF(rep);
5601 Py_XDECREF(errorHandler);
5602 Py_XDECREF(exc);
5603 Py_XDECREF(v);
5604 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005605}
5606
Alexander Belopolsky40018472011-02-26 01:02:56 +00005607PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005608PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5609 Py_ssize_t size,
5610 const char *errors,
5611 int byteorder)
5612{
5613 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005614 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005615 if (tmp == NULL)
5616 return NULL;
5617 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5618 Py_DECREF(tmp);
5619 return result;
5620}
5621
5622PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005623PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005624{
Victor Stinnerb960b342011-11-20 19:12:52 +01005625 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005626}
5627
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628/* --- UTF-16 Codec ------------------------------------------------------- */
5629
Tim Peters772747b2001-08-09 22:21:55 +00005630PyObject *
5631PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005632 Py_ssize_t size,
5633 const char *errors,
5634 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635{
Walter Dörwald69652032004-09-07 20:24:22 +00005636 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5637}
5638
5639PyObject *
5640PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 Py_ssize_t size,
5642 const char *errors,
5643 int *byteorder,
5644 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005645{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005647 Py_ssize_t startinpos;
5648 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005649 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005650 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005651 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005652 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005653 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005654 PyObject *errorHandler = NULL;
5655 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005656 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005657
Tim Peters772747b2001-08-09 22:21:55 +00005658 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005659 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005660
5661 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005662 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005664 /* Check for BOM marks (U+FEFF) in the input and adjust current
5665 byte order setting accordingly. In native mode, the leading BOM
5666 mark is skipped, in all other modes, it is copied to the output
5667 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005668 if (bo == 0 && size >= 2) {
5669 const Py_UCS4 bom = (q[1] << 8) | q[0];
5670 if (bom == 0xFEFF) {
5671 q += 2;
5672 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005673 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005674 else if (bom == 0xFFFE) {
5675 q += 2;
5676 bo = 1;
5677 }
5678 if (byteorder)
5679 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005680 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005681
Antoine Pitrou63065d72012-05-15 23:48:04 +02005682 if (q == e) {
5683 if (consumed)
5684 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005685 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005686 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005687
Christian Heimes743e0cd2012-10-17 23:52:17 +02005688#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005689 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005690 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005691#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005692 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005693 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005694#endif
Tim Peters772747b2001-08-09 22:21:55 +00005695
Antoine Pitrou63065d72012-05-15 23:48:04 +02005696 /* Note: size will always be longer than the resulting Unicode
5697 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005698 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005699 writer.min_length = (e - q + 1) / 2;
5700 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005701 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005702
Antoine Pitrou63065d72012-05-15 23:48:04 +02005703 while (1) {
5704 Py_UCS4 ch = 0;
5705 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005706 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005707 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005708 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005709 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005710 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005711 native_ordering);
5712 else
5713 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005714 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005715 native_ordering);
5716 } else if (kind == PyUnicode_2BYTE_KIND) {
5717 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005718 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005719 native_ordering);
5720 } else {
5721 assert(kind == PyUnicode_4BYTE_KIND);
5722 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005723 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005724 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005725 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005726 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005727
Antoine Pitrou63065d72012-05-15 23:48:04 +02005728 switch (ch)
5729 {
5730 case 0:
5731 /* remaining byte at the end? (size should be even) */
5732 if (q == e || consumed)
5733 goto End;
5734 errmsg = "truncated data";
5735 startinpos = ((const char *)q) - starts;
5736 endinpos = ((const char *)e) - starts;
5737 break;
5738 /* The remaining input chars are ignored if the callback
5739 chooses to skip the input */
5740 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005741 q -= 2;
5742 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005743 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005744 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005745 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005746 endinpos = ((const char *)e) - starts;
5747 break;
5748 case 2:
5749 errmsg = "illegal encoding";
5750 startinpos = ((const char *)q) - 2 - starts;
5751 endinpos = startinpos + 2;
5752 break;
5753 case 3:
5754 errmsg = "illegal UTF-16 surrogate";
5755 startinpos = ((const char *)q) - 4 - starts;
5756 endinpos = startinpos + 2;
5757 break;
5758 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005759 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005760 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005761 continue;
5762 }
5763
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005764 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005765 errors,
5766 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005767 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005768 &starts,
5769 (const char **)&e,
5770 &startinpos,
5771 &endinpos,
5772 &exc,
5773 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005774 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005775 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005776 }
5777
Antoine Pitrou63065d72012-05-15 23:48:04 +02005778End:
Walter Dörwald69652032004-09-07 20:24:22 +00005779 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005780 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005781
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 Py_XDECREF(errorHandler);
5783 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005784 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005785
Benjamin Peterson29060642009-01-31 22:14:21 +00005786 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005787 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005788 Py_XDECREF(errorHandler);
5789 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 return NULL;
5791}
5792
Tim Peters772747b2001-08-09 22:21:55 +00005793PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005794_PyUnicode_EncodeUTF16(PyObject *str,
5795 const char *errors,
5796 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005797{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005798 enum PyUnicode_Kind kind;
5799 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005800 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005801 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005802 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005803 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005804#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005805 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005806#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005807 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005808#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005809 const char *encoding;
5810 Py_ssize_t nsize, pos;
5811 PyObject *errorHandler = NULL;
5812 PyObject *exc = NULL;
5813 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005814
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005815 if (!PyUnicode_Check(str)) {
5816 PyErr_BadArgument();
5817 return NULL;
5818 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005819 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005820 return NULL;
5821 kind = PyUnicode_KIND(str);
5822 data = PyUnicode_DATA(str);
5823 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005824
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005825 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005826 if (kind == PyUnicode_4BYTE_KIND) {
5827 const Py_UCS4 *in = (const Py_UCS4 *)data;
5828 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005829 while (in < end) {
5830 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005831 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005832 }
5833 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005834 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005835 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005837 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005838 nsize = len + pairs + (byteorder == 0);
5839 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005840 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005841 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005842 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005844 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005845 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005846 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005847 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005848 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005849 }
5850 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005851 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005852 }
Tim Peters772747b2001-08-09 22:21:55 +00005853
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005854 if (kind == PyUnicode_1BYTE_KIND) {
5855 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5856 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005857 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005858
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005859 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005860 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005861 }
5862 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005863 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005864 }
5865 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005866 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005867 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005868
5869 pos = 0;
5870 while (pos < len) {
5871 Py_ssize_t repsize, moreunits;
5872
5873 if (kind == PyUnicode_2BYTE_KIND) {
5874 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5875 &out, native_ordering);
5876 }
5877 else {
5878 assert(kind == PyUnicode_4BYTE_KIND);
5879 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5880 &out, native_ordering);
5881 }
5882 if (pos == len)
5883 break;
5884
5885 rep = unicode_encode_call_errorhandler(
5886 errors, &errorHandler,
5887 encoding, "surrogates not allowed",
5888 str, &exc, pos, pos + 1, &pos);
5889 if (!rep)
5890 goto error;
5891
5892 if (PyBytes_Check(rep)) {
5893 repsize = PyBytes_GET_SIZE(rep);
5894 if (repsize & 1) {
5895 raise_encode_exception(&exc, encoding,
5896 str, pos - 1, pos,
5897 "surrogates not allowed");
5898 goto error;
5899 }
5900 moreunits = repsize / 2;
5901 }
5902 else {
5903 assert(PyUnicode_Check(rep));
5904 if (PyUnicode_READY(rep) < 0)
5905 goto error;
5906 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5907 if (!PyUnicode_IS_ASCII(rep)) {
5908 raise_encode_exception(&exc, encoding,
5909 str, pos - 1, pos,
5910 "surrogates not allowed");
5911 goto error;
5912 }
5913 }
5914
5915 /* two bytes are reserved for each surrogate */
5916 if (moreunits > 1) {
5917 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005918 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005919 /* integer overflow */
5920 PyErr_NoMemory();
5921 goto error;
5922 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005923 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005924 goto error;
5925 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5926 }
5927
5928 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005929 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005930 out += moreunits;
5931 } else /* rep is unicode */ {
5932 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5933 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5934 &out, native_ordering);
5935 }
5936
5937 Py_CLEAR(rep);
5938 }
5939
5940 /* Cut back to size actually needed. This is necessary for, for example,
5941 encoding of a string containing isolated surrogates and the 'ignore' handler
5942 is used. */
5943 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5944 if (nsize != PyBytes_GET_SIZE(v))
5945 _PyBytes_Resize(&v, nsize);
5946 Py_XDECREF(errorHandler);
5947 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005948 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005949 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005950 error:
5951 Py_XDECREF(rep);
5952 Py_XDECREF(errorHandler);
5953 Py_XDECREF(exc);
5954 Py_XDECREF(v);
5955 return NULL;
5956#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957}
5958
Alexander Belopolsky40018472011-02-26 01:02:56 +00005959PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005960PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5961 Py_ssize_t size,
5962 const char *errors,
5963 int byteorder)
5964{
5965 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005966 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005967 if (tmp == NULL)
5968 return NULL;
5969 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5970 Py_DECREF(tmp);
5971 return result;
5972}
5973
5974PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005975PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005977 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978}
5979
5980/* --- Unicode Escape Codec ----------------------------------------------- */
5981
Fredrik Lundh06d12682001-01-24 07:59:11 +00005982static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005983
Alexander Belopolsky40018472011-02-26 01:02:56 +00005984PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005985_PyUnicode_DecodeUnicodeEscape(const char *s,
5986 Py_ssize_t size,
5987 const char *errors,
5988 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005990 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005991 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005993 PyObject *errorHandler = NULL;
5994 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005995
Eric V. Smith42454af2016-10-31 09:22:08 -04005996 // so we can remember if we've seen an invalid escape char or not
5997 *first_invalid_escape = NULL;
5998
Victor Stinner62ec3312016-09-06 17:04:34 -07005999 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006000 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 }
6002 /* Escaped strings will always be longer than the resulting
6003 Unicode string, so we start with size here and then reduce the
6004 length after conversion to the true value.
6005 (but if the error callback returns a long replacement string
6006 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006007 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006008 writer.min_length = size;
6009 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6010 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006011 }
6012
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013 end = s + size;
6014 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006015 unsigned char c = (unsigned char) *s++;
6016 Py_UCS4 ch;
6017 int count;
6018 Py_ssize_t startinpos;
6019 Py_ssize_t endinpos;
6020 const char *message;
6021
6022#define WRITE_ASCII_CHAR(ch) \
6023 do { \
6024 assert(ch <= 127); \
6025 assert(writer.pos < writer.size); \
6026 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6027 } while(0)
6028
6029#define WRITE_CHAR(ch) \
6030 do { \
6031 if (ch <= writer.maxchar) { \
6032 assert(writer.pos < writer.size); \
6033 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6034 } \
6035 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6036 goto onError; \
6037 } \
6038 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039
6040 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006041 if (c != '\\') {
6042 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 continue;
6044 }
6045
Victor Stinner62ec3312016-09-06 17:04:34 -07006046 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006048 if (s >= end) {
6049 message = "\\ at end of string";
6050 goto error;
6051 }
6052 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006053
Victor Stinner62ec3312016-09-06 17:04:34 -07006054 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006055 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056
Benjamin Peterson29060642009-01-31 22:14:21 +00006057 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006058 case '\n': continue;
6059 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6060 case '\'': WRITE_ASCII_CHAR('\''); continue;
6061 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6062 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006063 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006064 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6065 case 't': WRITE_ASCII_CHAR('\t'); continue;
6066 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6067 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006068 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006069 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006070 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074 case '0': case '1': case '2': case '3':
6075 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006076 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006077 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006078 ch = (ch<<3) + *s++ - '0';
6079 if (s < end && '0' <= *s && *s <= '7') {
6080 ch = (ch<<3) + *s++ - '0';
6081 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006083 WRITE_CHAR(ch);
6084 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 /* hex escapes */
6087 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006089 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006090 message = "truncated \\xXX escape";
6091 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006095 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006096 message = "truncated \\uXXXX escape";
6097 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098
Benjamin Peterson29060642009-01-31 22:14:21 +00006099 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006100 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006101 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006102 message = "truncated \\UXXXXXXXX escape";
6103 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006104 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006105 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006106 ch <<= 4;
6107 if (c >= '0' && c <= '9') {
6108 ch += c - '0';
6109 }
6110 else if (c >= 'a' && c <= 'f') {
6111 ch += c - ('a' - 10);
6112 }
6113 else if (c >= 'A' && c <= 'F') {
6114 ch += c - ('A' - 10);
6115 }
6116 else {
6117 break;
6118 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006119 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006120 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006121 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006122 }
6123
6124 /* when we get here, ch is a 32-bit unicode character */
6125 if (ch > MAX_UNICODE) {
6126 message = "illegal Unicode character";
6127 goto error;
6128 }
6129
6130 WRITE_CHAR(ch);
6131 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006132
Benjamin Peterson29060642009-01-31 22:14:21 +00006133 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006134 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006135 if (ucnhash_CAPI == NULL) {
6136 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006137 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6138 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 if (ucnhash_CAPI == NULL) {
6140 PyErr_SetString(
6141 PyExc_UnicodeError,
6142 "\\N escapes not supported (can't load unicodedata module)"
6143 );
6144 goto onError;
6145 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006146 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006147
6148 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006149 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006150 const char *start = ++s;
6151 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006152 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006153 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006154 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006155 namelen = s - start;
6156 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006157 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006158 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006159 ch = 0xffffffff; /* in case 'getcode' messes up */
6160 if (namelen <= INT_MAX &&
6161 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6162 &ch, 0)) {
6163 assert(ch <= MAX_UNICODE);
6164 WRITE_CHAR(ch);
6165 continue;
6166 }
6167 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006168 }
6169 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006170 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006171
6172 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006173 if (*first_invalid_escape == NULL) {
6174 *first_invalid_escape = s-1; /* Back up one char, since we've
6175 already incremented s. */
6176 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 WRITE_ASCII_CHAR('\\');
6178 WRITE_CHAR(c);
6179 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006181
6182 error:
6183 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006184 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006185 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006186 errors, &errorHandler,
6187 "unicodeescape", message,
6188 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006189 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006190 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 }
6192 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6193 goto onError;
6194 }
6195
6196#undef WRITE_ASCII_CHAR
6197#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006199
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006200 Py_XDECREF(errorHandler);
6201 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006202 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006203
Benjamin Peterson29060642009-01-31 22:14:21 +00006204 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006205 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006206 Py_XDECREF(errorHandler);
6207 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 return NULL;
6209}
6210
Eric V. Smith42454af2016-10-31 09:22:08 -04006211PyObject *
6212PyUnicode_DecodeUnicodeEscape(const char *s,
6213 Py_ssize_t size,
6214 const char *errors)
6215{
6216 const char *first_invalid_escape;
6217 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6218 &first_invalid_escape);
6219 if (result == NULL)
6220 return NULL;
6221 if (first_invalid_escape != NULL) {
6222 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6223 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006224 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006225 Py_DECREF(result);
6226 return NULL;
6227 }
6228 }
6229 return result;
6230}
6231
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006232/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233
Alexander Belopolsky40018472011-02-26 01:02:56 +00006234PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006235PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006238 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006240 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006241 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006242 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243
Ezio Melottie7f90372012-10-05 03:33:31 +03006244 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006245 escape.
6246
Ezio Melottie7f90372012-10-05 03:33:31 +03006247 For UCS1 strings it's '\xxx', 4 bytes per source character.
6248 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6249 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006250 */
6251
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006252 if (!PyUnicode_Check(unicode)) {
6253 PyErr_BadArgument();
6254 return NULL;
6255 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006256 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006257 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006258 }
Victor Stinner358af132015-10-12 22:36:57 +02006259
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006260 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006261 if (len == 0) {
6262 return PyBytes_FromStringAndSize(NULL, 0);
6263 }
6264
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006265 kind = PyUnicode_KIND(unicode);
6266 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006267 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6268 bytes, and 1 byte characters 4. */
6269 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006270 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006271 return PyErr_NoMemory();
6272 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006273 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 if (repr == NULL) {
6275 return NULL;
6276 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006277
Victor Stinner62ec3312016-09-06 17:04:34 -07006278 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006279 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006280 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006281
Victor Stinner62ec3312016-09-06 17:04:34 -07006282 /* U+0000-U+00ff range */
6283 if (ch < 0x100) {
6284 if (ch >= ' ' && ch < 127) {
6285 if (ch != '\\') {
6286 /* Copy printable US ASCII as-is */
6287 *p++ = (char) ch;
6288 }
6289 /* Escape backslashes */
6290 else {
6291 *p++ = '\\';
6292 *p++ = '\\';
6293 }
6294 }
Victor Stinner358af132015-10-12 22:36:57 +02006295
Victor Stinner62ec3312016-09-06 17:04:34 -07006296 /* Map special whitespace to '\t', \n', '\r' */
6297 else if (ch == '\t') {
6298 *p++ = '\\';
6299 *p++ = 't';
6300 }
6301 else if (ch == '\n') {
6302 *p++ = '\\';
6303 *p++ = 'n';
6304 }
6305 else if (ch == '\r') {
6306 *p++ = '\\';
6307 *p++ = 'r';
6308 }
6309
6310 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6311 else {
6312 *p++ = '\\';
6313 *p++ = 'x';
6314 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6315 *p++ = Py_hexdigits[ch & 0x000F];
6316 }
Tim Petersced69f82003-09-16 20:30:58 +00006317 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006318 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320 *p++ = '\\';
6321 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006322 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6323 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6324 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6325 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006326 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006327 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6328 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006329
Victor Stinner62ec3312016-09-06 17:04:34 -07006330 /* Make sure that the first two digits are zero */
6331 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006332 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006333 *p++ = 'U';
6334 *p++ = '0';
6335 *p++ = '0';
6336 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6337 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6338 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6339 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6340 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6341 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006342 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344
Victor Stinner62ec3312016-09-06 17:04:34 -07006345 assert(p - PyBytes_AS_STRING(repr) > 0);
6346 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6347 return NULL;
6348 }
6349 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350}
6351
Alexander Belopolsky40018472011-02-26 01:02:56 +00006352PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006353PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6354 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006355{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006356 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006357 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006358 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006359 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006360 }
6361
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006362 result = PyUnicode_AsUnicodeEscapeString(tmp);
6363 Py_DECREF(tmp);
6364 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006365}
6366
6367/* --- Raw Unicode Escape Codec ------------------------------------------- */
6368
Alexander Belopolsky40018472011-02-26 01:02:56 +00006369PyObject *
6370PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006371 Py_ssize_t size,
6372 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006373{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006374 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006375 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377 PyObject *errorHandler = NULL;
6378 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006379
Victor Stinner62ec3312016-09-06 17:04:34 -07006380 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006381 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006382 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006383
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384 /* Escaped strings will always be longer than the resulting
6385 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386 length after conversion to the true value. (But decoding error
6387 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006388 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006389 writer.min_length = size;
6390 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6391 goto onError;
6392 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006393
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394 end = s + size;
6395 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 unsigned char c = (unsigned char) *s++;
6397 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006398 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006399 Py_ssize_t startinpos;
6400 Py_ssize_t endinpos;
6401 const char *message;
6402
6403#define WRITE_CHAR(ch) \
6404 do { \
6405 if (ch <= writer.maxchar) { \
6406 assert(writer.pos < writer.size); \
6407 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6408 } \
6409 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6410 goto onError; \
6411 } \
6412 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 if (c != '\\' || s >= end) {
6416 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006418 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006419
Victor Stinner62ec3312016-09-06 17:04:34 -07006420 c = (unsigned char) *s++;
6421 if (c == 'u') {
6422 count = 4;
6423 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 else if (c == 'U') {
6426 count = 8;
6427 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006428 }
6429 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006430 assert(writer.pos < writer.size);
6431 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6432 WRITE_CHAR(c);
6433 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006434 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006435 startinpos = s - starts - 2;
6436
6437 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6438 for (ch = 0; count && s < end; ++s, --count) {
6439 c = (unsigned char)*s;
6440 ch <<= 4;
6441 if (c >= '0' && c <= '9') {
6442 ch += c - '0';
6443 }
6444 else if (c >= 'a' && c <= 'f') {
6445 ch += c - ('a' - 10);
6446 }
6447 else if (c >= 'A' && c <= 'F') {
6448 ch += c - ('A' - 10);
6449 }
6450 else {
6451 break;
6452 }
6453 }
6454 if (!count) {
6455 if (ch <= MAX_UNICODE) {
6456 WRITE_CHAR(ch);
6457 continue;
6458 }
6459 message = "\\Uxxxxxxxx out of range";
6460 }
6461
6462 endinpos = s-starts;
6463 writer.min_length = end - s + writer.pos;
6464 if (unicode_decode_call_errorhandler_writer(
6465 errors, &errorHandler,
6466 "rawunicodeescape", message,
6467 &starts, &end, &startinpos, &endinpos, &exc, &s,
6468 &writer)) {
6469 goto onError;
6470 }
6471 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6472 goto onError;
6473 }
6474
6475#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006476 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006477 Py_XDECREF(errorHandler);
6478 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006479 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006480
Benjamin Peterson29060642009-01-31 22:14:21 +00006481 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006482 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 Py_XDECREF(errorHandler);
6484 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006485 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006486
Guido van Rossumd57fd912000-03-10 22:53:23 +00006487}
6488
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006489
Alexander Belopolsky40018472011-02-26 01:02:56 +00006490PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006491PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006492{
Victor Stinner62ec3312016-09-06 17:04:34 -07006493 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006495 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006496 int kind;
6497 void *data;
6498 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006499
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006500 if (!PyUnicode_Check(unicode)) {
6501 PyErr_BadArgument();
6502 return NULL;
6503 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006504 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006505 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006506 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006507 kind = PyUnicode_KIND(unicode);
6508 data = PyUnicode_DATA(unicode);
6509 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006510 if (kind == PyUnicode_1BYTE_KIND) {
6511 return PyBytes_FromStringAndSize(data, len);
6512 }
Victor Stinner0e368262011-11-10 20:12:49 +01006513
Victor Stinner62ec3312016-09-06 17:04:34 -07006514 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6515 bytes, and 1 byte characters 4. */
6516 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006517
Victor Stinner62ec3312016-09-06 17:04:34 -07006518 if (len > PY_SSIZE_T_MAX / expandsize) {
6519 return PyErr_NoMemory();
6520 }
6521 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6522 if (repr == NULL) {
6523 return NULL;
6524 }
6525 if (len == 0) {
6526 return repr;
6527 }
6528
6529 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006530 for (pos = 0; pos < len; pos++) {
6531 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006532
Victor Stinner62ec3312016-09-06 17:04:34 -07006533 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6534 if (ch < 0x100) {
6535 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006536 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006537 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6538 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006539 *p++ = '\\';
6540 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006541 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6542 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6543 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6544 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006545 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006546 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6547 else {
6548 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6549 *p++ = '\\';
6550 *p++ = 'U';
6551 *p++ = '0';
6552 *p++ = '0';
6553 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6554 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6555 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6556 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6557 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6558 *p++ = Py_hexdigits[ch & 15];
6559 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006560 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006561
Victor Stinner62ec3312016-09-06 17:04:34 -07006562 assert(p > PyBytes_AS_STRING(repr));
6563 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6564 return NULL;
6565 }
6566 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006567}
6568
Alexander Belopolsky40018472011-02-26 01:02:56 +00006569PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006570PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6571 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006573 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006574 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006575 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006576 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006577 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6578 Py_DECREF(tmp);
6579 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006580}
6581
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006582/* --- Unicode Internal Codec ------------------------------------------- */
6583
Alexander Belopolsky40018472011-02-26 01:02:56 +00006584PyObject *
6585_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006586 Py_ssize_t size,
6587 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006588{
6589 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006590 Py_ssize_t startinpos;
6591 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006592 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006593 const char *end;
6594 const char *reason;
6595 PyObject *errorHandler = NULL;
6596 PyObject *exc = NULL;
6597
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006598 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006599 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006600 1))
6601 return NULL;
6602
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006603 if (size < 0) {
6604 PyErr_BadInternalCall();
6605 return NULL;
6606 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006607 if (size == 0)
6608 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006609
Victor Stinner8f674cc2013-04-17 23:02:17 +02006610 _PyUnicodeWriter_Init(&writer);
6611 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6612 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006614 }
6615 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006616
Victor Stinner8f674cc2013-04-17 23:02:17 +02006617 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006618 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006619 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006620 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006621 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006622 endinpos = end-starts;
6623 reason = "truncated input";
6624 goto error;
6625 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006626 /* We copy the raw representation one byte at a time because the
6627 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006628 ((char *) &uch)[0] = s[0];
6629 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006630#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006631 ((char *) &uch)[2] = s[2];
6632 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006633#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006634 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006635#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006636 /* We have to sanity check the raw data, otherwise doom looms for
6637 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006638 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006639 endinpos = s - starts + Py_UNICODE_SIZE;
6640 reason = "illegal code point (> 0x10FFFF)";
6641 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006642 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006643#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006644 s += Py_UNICODE_SIZE;
6645#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006646 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006647 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006648 Py_UNICODE uch2;
6649 ((char *) &uch2)[0] = s[0];
6650 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006651 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006652 {
Victor Stinner551ac952011-11-29 22:58:13 +01006653 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006654 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006655 }
6656 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006657#endif
6658
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006659 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006660 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006661 continue;
6662
6663 error:
6664 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006665 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006666 errors, &errorHandler,
6667 "unicode_internal", reason,
6668 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006669 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006670 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006671 }
6672
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006673 Py_XDECREF(errorHandler);
6674 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006675 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006676
Benjamin Peterson29060642009-01-31 22:14:21 +00006677 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006678 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006679 Py_XDECREF(errorHandler);
6680 Py_XDECREF(exc);
6681 return NULL;
6682}
6683
Guido van Rossumd57fd912000-03-10 22:53:23 +00006684/* --- Latin-1 Codec ------------------------------------------------------ */
6685
Alexander Belopolsky40018472011-02-26 01:02:56 +00006686PyObject *
6687PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006688 Py_ssize_t size,
6689 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006690{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006692 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006693}
6694
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006696static void
6697make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006698 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006699 PyObject *unicode,
6700 Py_ssize_t startpos, Py_ssize_t endpos,
6701 const char *reason)
6702{
6703 if (*exceptionObject == NULL) {
6704 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006705 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006706 encoding, unicode, startpos, endpos, reason);
6707 }
6708 else {
6709 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6710 goto onError;
6711 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6712 goto onError;
6713 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6714 goto onError;
6715 return;
6716 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006717 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006718 }
6719}
6720
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006722static void
6723raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006724 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006725 PyObject *unicode,
6726 Py_ssize_t startpos, Py_ssize_t endpos,
6727 const char *reason)
6728{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006729 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006730 encoding, unicode, startpos, endpos, reason);
6731 if (*exceptionObject != NULL)
6732 PyCodec_StrictErrors(*exceptionObject);
6733}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006734
6735/* error handling callback helper:
6736 build arguments, call the callback and check the arguments,
6737 put the result into newpos and return the replacement string, which
6738 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006739static PyObject *
6740unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006741 PyObject **errorHandler,
6742 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006743 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006744 Py_ssize_t startpos, Py_ssize_t endpos,
6745 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006747 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006748 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006749 PyObject *restuple;
6750 PyObject *resunicode;
6751
6752 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006756 }
6757
Benjamin Petersonbac79492012-01-14 13:34:47 -05006758 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006759 return NULL;
6760 len = PyUnicode_GET_LENGTH(unicode);
6761
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006762 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006763 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006764 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006766
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006767 restuple = PyObject_CallFunctionObjArgs(
6768 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006769 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006771 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006772 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006773 Py_DECREF(restuple);
6774 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006775 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006776 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 &resunicode, newpos)) {
6778 Py_DECREF(restuple);
6779 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006780 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006781 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6782 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6783 Py_DECREF(restuple);
6784 return NULL;
6785 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006786 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006787 *newpos = len + *newpos;
6788 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006789 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 Py_DECREF(restuple);
6791 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006792 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006793 Py_INCREF(resunicode);
6794 Py_DECREF(restuple);
6795 return resunicode;
6796}
6797
Alexander Belopolsky40018472011-02-26 01:02:56 +00006798static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006799unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006800 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006801 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006802{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006803 /* input state */
6804 Py_ssize_t pos=0, size;
6805 int kind;
6806 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006807 /* pointer into the output */
6808 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006809 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6810 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006811 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006812 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006813 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006815 /* output object */
6816 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006817
Benjamin Petersonbac79492012-01-14 13:34:47 -05006818 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006819 return NULL;
6820 size = PyUnicode_GET_LENGTH(unicode);
6821 kind = PyUnicode_KIND(unicode);
6822 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006823 /* allocate enough for a simple encoding without
6824 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006825 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006826 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006827
6828 _PyBytesWriter_Init(&writer);
6829 str = _PyBytesWriter_Alloc(&writer, size);
6830 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006831 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006832
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006833 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006834 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006835
Benjamin Peterson29060642009-01-31 22:14:21 +00006836 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006837 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006838 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006839 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006840 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006841 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006843 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006844 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006846 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006848
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006849 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006850 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006851
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006852 /* Only overallocate the buffer if it's not the last write */
6853 writer.overallocate = (collend < size);
6854
Benjamin Peterson29060642009-01-31 22:14:21 +00006855 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006856 if (error_handler == _Py_ERROR_UNKNOWN)
6857 error_handler = get_error_handler(errors);
6858
6859 switch (error_handler) {
6860 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006861 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006863
6864 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006865 memset(str, '?', collend - collstart);
6866 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006867 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006868 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006869 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006870 break;
Victor Stinner50149202015-09-22 00:26:54 +02006871
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006872 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006873 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006874 writer.min_size -= (collend - collstart);
6875 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006876 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006877 if (str == NULL)
6878 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006879 pos = collend;
6880 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006881
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006882 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006883 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006884 writer.min_size -= (collend - collstart);
6885 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006886 unicode, collstart, collend);
6887 if (str == NULL)
6888 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006889 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006890 break;
Victor Stinner50149202015-09-22 00:26:54 +02006891
Victor Stinnerc3713e92015-09-29 12:32:13 +02006892 case _Py_ERROR_SURROGATEESCAPE:
6893 for (i = collstart; i < collend; ++i) {
6894 ch = PyUnicode_READ(kind, data, i);
6895 if (ch < 0xdc80 || 0xdcff < ch) {
6896 /* Not a UTF-8b surrogate */
6897 break;
6898 }
6899 *str++ = (char)(ch - 0xdc00);
6900 ++pos;
6901 }
6902 if (i >= collend)
6903 break;
6904 collstart = pos;
6905 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006906 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006907
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006909 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6910 encoding, reason, unicode, &exc,
6911 collstart, collend, &newpos);
6912 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006913 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006914
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006915 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006916 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006917
Victor Stinner6bd525b2015-10-09 13:10:05 +02006918 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006919 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006920 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006921 PyBytes_AS_STRING(rep),
6922 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006923 if (str == NULL)
6924 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006925 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006926 else {
6927 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006928
Victor Stinner6bd525b2015-10-09 13:10:05 +02006929 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006930 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006931
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006932 if (limit == 256 ?
6933 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6934 !PyUnicode_IS_ASCII(rep))
6935 {
6936 /* Not all characters are smaller than limit */
6937 raise_encode_exception(&exc, encoding, unicode,
6938 collstart, collend, reason);
6939 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006941 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6942 str = _PyBytesWriter_WriteBytes(&writer, str,
6943 PyUnicode_DATA(rep),
6944 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006945 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006946 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006947 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006948 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006949
6950 /* If overallocation was disabled, ensure that it was the last
6951 write. Otherwise, we missed an optimization */
6952 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006953 }
6954 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006955
Victor Stinner50149202015-09-22 00:26:54 +02006956 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006957 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006958 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006959
6960 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006961 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006962 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006963 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006964 Py_XDECREF(exc);
6965 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006966}
6967
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006968/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006969PyObject *
6970PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006971 Py_ssize_t size,
6972 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006973{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006974 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006975 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006976 if (unicode == NULL)
6977 return NULL;
6978 result = unicode_encode_ucs1(unicode, errors, 256);
6979 Py_DECREF(unicode);
6980 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006981}
6982
Alexander Belopolsky40018472011-02-26 01:02:56 +00006983PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006984_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985{
6986 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 PyErr_BadArgument();
6988 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006990 if (PyUnicode_READY(unicode) == -1)
6991 return NULL;
6992 /* Fast path: if it is a one-byte string, construct
6993 bytes object directly. */
6994 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6995 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6996 PyUnicode_GET_LENGTH(unicode));
6997 /* Non-Latin-1 characters present. Defer to above function to
6998 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006999 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007000}
7001
7002PyObject*
7003PyUnicode_AsLatin1String(PyObject *unicode)
7004{
7005 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007006}
7007
7008/* --- 7-bit ASCII Codec -------------------------------------------------- */
7009
Alexander Belopolsky40018472011-02-26 01:02:56 +00007010PyObject *
7011PyUnicode_DecodeASCII(const char *s,
7012 Py_ssize_t size,
7013 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007014{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007015 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007016 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007017 int kind;
7018 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007019 Py_ssize_t startinpos;
7020 Py_ssize_t endinpos;
7021 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007022 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007023 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007024 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007025 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00007026
Guido van Rossumd57fd912000-03-10 22:53:23 +00007027 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02007028 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007029
Guido van Rossumd57fd912000-03-10 22:53:23 +00007030 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02007031 if (size == 1 && (unsigned char)s[0] < 128)
7032 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007033
Victor Stinner8f674cc2013-04-17 23:02:17 +02007034 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007035 writer.min_length = size;
7036 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02007037 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007038
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007039 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007040 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007041 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007042 writer.pos = outpos;
7043 if (writer.pos == size)
7044 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007045
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007046 s += writer.pos;
7047 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007048 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007049 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007050 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007051 PyUnicode_WRITE(kind, data, writer.pos, c);
7052 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007053 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007054 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007055 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007056
7057 /* byte outsize range 0x00..0x7f: call the error handler */
7058
7059 if (error_handler == _Py_ERROR_UNKNOWN)
7060 error_handler = get_error_handler(errors);
7061
7062 switch (error_handler)
7063 {
7064 case _Py_ERROR_REPLACE:
7065 case _Py_ERROR_SURROGATEESCAPE:
7066 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007067 but we may switch to UCS2 at the first write */
7068 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7069 goto onError;
7070 kind = writer.kind;
7071 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007072
7073 if (error_handler == _Py_ERROR_REPLACE)
7074 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7075 else
7076 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7077 writer.pos++;
7078 ++s;
7079 break;
7080
7081 case _Py_ERROR_IGNORE:
7082 ++s;
7083 break;
7084
7085 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 startinpos = s-starts;
7087 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007088 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007089 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 "ascii", "ordinal not in range(128)",
7091 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007092 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007093 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007094 kind = writer.kind;
7095 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007096 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007097 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007098 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007099 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007100 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007101
Benjamin Peterson29060642009-01-31 22:14:21 +00007102 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007103 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007104 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007105 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007106 return NULL;
7107}
7108
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007109/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007110PyObject *
7111PyUnicode_EncodeASCII(const Py_UNICODE *p,
7112 Py_ssize_t size,
7113 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007114{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007115 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007116 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007117 if (unicode == NULL)
7118 return NULL;
7119 result = unicode_encode_ucs1(unicode, errors, 128);
7120 Py_DECREF(unicode);
7121 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007122}
7123
Alexander Belopolsky40018472011-02-26 01:02:56 +00007124PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007125_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007126{
7127 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007128 PyErr_BadArgument();
7129 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007130 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007131 if (PyUnicode_READY(unicode) == -1)
7132 return NULL;
7133 /* Fast path: if it is an ASCII-only string, construct bytes object
7134 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007135 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007136 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7137 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007138 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007139}
7140
7141PyObject *
7142PyUnicode_AsASCIIString(PyObject *unicode)
7143{
7144 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007145}
7146
Steve Dowercc16be82016-09-08 10:35:16 -07007147#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007148
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007149/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007150
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007151#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007152#define NEED_RETRY
7153#endif
7154
Victor Stinner3a50e702011-10-18 21:21:00 +02007155#ifndef WC_ERR_INVALID_CHARS
7156# define WC_ERR_INVALID_CHARS 0x0080
7157#endif
7158
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007159static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007160code_page_name(UINT code_page, PyObject **obj)
7161{
7162 *obj = NULL;
7163 if (code_page == CP_ACP)
7164 return "mbcs";
7165 if (code_page == CP_UTF7)
7166 return "CP_UTF7";
7167 if (code_page == CP_UTF8)
7168 return "CP_UTF8";
7169
7170 *obj = PyBytes_FromFormat("cp%u", code_page);
7171 if (*obj == NULL)
7172 return NULL;
7173 return PyBytes_AS_STRING(*obj);
7174}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007175
Victor Stinner3a50e702011-10-18 21:21:00 +02007176static DWORD
7177decode_code_page_flags(UINT code_page)
7178{
7179 if (code_page == CP_UTF7) {
7180 /* The CP_UTF7 decoder only supports flags=0 */
7181 return 0;
7182 }
7183 else
7184 return MB_ERR_INVALID_CHARS;
7185}
7186
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007187/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 * Decode a byte string from a Windows code page into unicode object in strict
7189 * mode.
7190 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007191 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7192 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007193 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007194static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007195decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007196 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 const char *in,
7198 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007199{
Victor Stinner3a50e702011-10-18 21:21:00 +02007200 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007201 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007203
7204 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 assert(insize > 0);
7206 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7207 if (outsize <= 0)
7208 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007209
7210 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007211 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007212 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007213 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007214 if (*v == NULL)
7215 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007217 }
7218 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007219 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007221 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007222 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007224 }
7225
7226 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7228 if (outsize <= 0)
7229 goto error;
7230 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007231
Victor Stinner3a50e702011-10-18 21:21:00 +02007232error:
7233 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7234 return -2;
7235 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007236 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007237}
7238
Victor Stinner3a50e702011-10-18 21:21:00 +02007239/*
7240 * Decode a byte string from a code page into unicode object with an error
7241 * handler.
7242 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007243 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 * UnicodeDecodeError exception and returns -1 on error.
7245 */
7246static int
7247decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007248 PyObject **v,
7249 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007250 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007251{
7252 const char *startin = in;
7253 const char *endin = in + size;
7254 const DWORD flags = decode_code_page_flags(code_page);
7255 /* Ideally, we should get reason from FormatMessage. This is the Windows
7256 2000 English version of the message. */
7257 const char *reason = "No mapping for the Unicode character exists "
7258 "in the target code page.";
7259 /* each step cannot decode more than 1 character, but a character can be
7260 represented as a surrogate pair */
7261 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007262 int insize;
7263 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 PyObject *errorHandler = NULL;
7265 PyObject *exc = NULL;
7266 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007267 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007268 DWORD err;
7269 int ret = -1;
7270
7271 assert(size > 0);
7272
7273 encoding = code_page_name(code_page, &encoding_obj);
7274 if (encoding == NULL)
7275 return -1;
7276
Victor Stinner7d00cc12014-03-17 23:08:06 +01007277 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7279 UnicodeDecodeError. */
7280 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7281 if (exc != NULL) {
7282 PyCodec_StrictErrors(exc);
7283 Py_CLEAR(exc);
7284 }
7285 goto error;
7286 }
7287
7288 if (*v == NULL) {
7289 /* Create unicode object */
7290 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7291 PyErr_NoMemory();
7292 goto error;
7293 }
Victor Stinnerab595942011-12-17 04:59:06 +01007294 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007296 if (*v == NULL)
7297 goto error;
7298 startout = PyUnicode_AS_UNICODE(*v);
7299 }
7300 else {
7301 /* Extend unicode object */
7302 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7303 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7304 PyErr_NoMemory();
7305 goto error;
7306 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007307 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 goto error;
7309 startout = PyUnicode_AS_UNICODE(*v) + n;
7310 }
7311
7312 /* Decode the byte string character per character */
7313 out = startout;
7314 while (in < endin)
7315 {
7316 /* Decode a character */
7317 insize = 1;
7318 do
7319 {
7320 outsize = MultiByteToWideChar(code_page, flags,
7321 in, insize,
7322 buffer, Py_ARRAY_LENGTH(buffer));
7323 if (outsize > 0)
7324 break;
7325 err = GetLastError();
7326 if (err != ERROR_NO_UNICODE_TRANSLATION
7327 && err != ERROR_INSUFFICIENT_BUFFER)
7328 {
7329 PyErr_SetFromWindowsErr(0);
7330 goto error;
7331 }
7332 insize++;
7333 }
7334 /* 4=maximum length of a UTF-8 sequence */
7335 while (insize <= 4 && (in + insize) <= endin);
7336
7337 if (outsize <= 0) {
7338 Py_ssize_t startinpos, endinpos, outpos;
7339
Victor Stinner7d00cc12014-03-17 23:08:06 +01007340 /* last character in partial decode? */
7341 if (in + insize >= endin && !final)
7342 break;
7343
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 startinpos = in - startin;
7345 endinpos = startinpos + 1;
7346 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007347 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007348 errors, &errorHandler,
7349 encoding, reason,
7350 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007351 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007352 {
7353 goto error;
7354 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007355 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007356 }
7357 else {
7358 in += insize;
7359 memcpy(out, buffer, outsize * sizeof(wchar_t));
7360 out += outsize;
7361 }
7362 }
7363
7364 /* write a NUL character at the end */
7365 *out = 0;
7366
7367 /* Extend unicode object */
7368 outsize = out - startout;
7369 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007370 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007372 /* (in - startin) <= size and size is an int */
7373 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007374
7375error:
7376 Py_XDECREF(encoding_obj);
7377 Py_XDECREF(errorHandler);
7378 Py_XDECREF(exc);
7379 return ret;
7380}
7381
Victor Stinner3a50e702011-10-18 21:21:00 +02007382static PyObject *
7383decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007384 const char *s, Py_ssize_t size,
7385 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386{
Victor Stinner76a31a62011-11-04 00:05:13 +01007387 PyObject *v = NULL;
7388 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007389
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 if (code_page < 0) {
7391 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7392 return NULL;
7393 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007394 if (size < 0) {
7395 PyErr_BadInternalCall();
7396 return NULL;
7397 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007398
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007399 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007400 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007401
Victor Stinner76a31a62011-11-04 00:05:13 +01007402 do
7403 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007404#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007405 if (size > INT_MAX) {
7406 chunk_size = INT_MAX;
7407 final = 0;
7408 done = 0;
7409 }
7410 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007411#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007412 {
7413 chunk_size = (int)size;
7414 final = (consumed == NULL);
7415 done = 1;
7416 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007417
Victor Stinner76a31a62011-11-04 00:05:13 +01007418 if (chunk_size == 0 && done) {
7419 if (v != NULL)
7420 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007421 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007422 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007423
Victor Stinner76a31a62011-11-04 00:05:13 +01007424 converted = decode_code_page_strict(code_page, &v,
7425 s, chunk_size);
7426 if (converted == -2)
7427 converted = decode_code_page_errors(code_page, &v,
7428 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007429 errors, final);
7430 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007431
7432 if (converted < 0) {
7433 Py_XDECREF(v);
7434 return NULL;
7435 }
7436
7437 if (consumed)
7438 *consumed += converted;
7439
7440 s += converted;
7441 size -= converted;
7442 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007443
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007444 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445}
7446
Alexander Belopolsky40018472011-02-26 01:02:56 +00007447PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007448PyUnicode_DecodeCodePageStateful(int code_page,
7449 const char *s,
7450 Py_ssize_t size,
7451 const char *errors,
7452 Py_ssize_t *consumed)
7453{
7454 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7455}
7456
7457PyObject *
7458PyUnicode_DecodeMBCSStateful(const char *s,
7459 Py_ssize_t size,
7460 const char *errors,
7461 Py_ssize_t *consumed)
7462{
7463 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7464}
7465
7466PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007467PyUnicode_DecodeMBCS(const char *s,
7468 Py_ssize_t size,
7469 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007470{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007471 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7472}
7473
Victor Stinner3a50e702011-10-18 21:21:00 +02007474static DWORD
7475encode_code_page_flags(UINT code_page, const char *errors)
7476{
7477 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007478 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 }
7480 else if (code_page == CP_UTF7) {
7481 /* CP_UTF7 only supports flags=0 */
7482 return 0;
7483 }
7484 else {
7485 if (errors != NULL && strcmp(errors, "replace") == 0)
7486 return 0;
7487 else
7488 return WC_NO_BEST_FIT_CHARS;
7489 }
7490}
7491
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007492/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007493 * Encode a Unicode string to a Windows code page into a byte string in strict
7494 * mode.
7495 *
7496 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007497 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007498 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007499static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007500encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007501 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007502 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503{
Victor Stinner554f3f02010-06-16 23:33:54 +00007504 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 BOOL *pusedDefaultChar = &usedDefaultChar;
7506 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007507 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007508 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 const DWORD flags = encode_code_page_flags(code_page, NULL);
7510 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007511 /* Create a substring so that we can get the UTF-16 representation
7512 of just the slice under consideration. */
7513 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007514
Martin v. Löwis3d325192011-11-04 18:23:06 +01007515 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007516
Victor Stinner3a50e702011-10-18 21:21:00 +02007517 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007518 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007519 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007520 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007521
Victor Stinner2fc507f2011-11-04 20:06:39 +01007522 substring = PyUnicode_Substring(unicode, offset, offset+len);
7523 if (substring == NULL)
7524 return -1;
7525 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7526 if (p == NULL) {
7527 Py_DECREF(substring);
7528 return -1;
7529 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007530 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007532 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007533 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007534 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007535 NULL, 0,
7536 NULL, pusedDefaultChar);
7537 if (outsize <= 0)
7538 goto error;
7539 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007540 if (pusedDefaultChar && *pusedDefaultChar) {
7541 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007542 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007543 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007544
Victor Stinner3a50e702011-10-18 21:21:00 +02007545 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007546 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007547 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007548 if (*outbytes == NULL) {
7549 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007550 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007551 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007552 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007553 }
7554 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007555 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007556 const Py_ssize_t n = PyBytes_Size(*outbytes);
7557 if (outsize > PY_SSIZE_T_MAX - n) {
7558 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007559 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007560 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007562 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7563 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007565 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007566 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007567 }
7568
7569 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007571 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007572 out, outsize,
7573 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007574 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 if (outsize <= 0)
7576 goto error;
7577 if (pusedDefaultChar && *pusedDefaultChar)
7578 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007579 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007580
Victor Stinner3a50e702011-10-18 21:21:00 +02007581error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007582 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007583 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7584 return -2;
7585 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007586 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007587}
7588
Victor Stinner3a50e702011-10-18 21:21:00 +02007589/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007590 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007591 * error handler.
7592 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007593 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007594 * -1 on other error.
7595 */
7596static int
7597encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007598 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007599 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007600{
Victor Stinner3a50e702011-10-18 21:21:00 +02007601 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007602 Py_ssize_t pos = unicode_offset;
7603 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007604 /* Ideally, we should get reason from FormatMessage. This is the Windows
7605 2000 English version of the message. */
7606 const char *reason = "invalid character";
7607 /* 4=maximum length of a UTF-8 sequence */
7608 char buffer[4];
7609 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7610 Py_ssize_t outsize;
7611 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007612 PyObject *errorHandler = NULL;
7613 PyObject *exc = NULL;
7614 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007615 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007616 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007617 PyObject *rep;
7618 int ret = -1;
7619
7620 assert(insize > 0);
7621
7622 encoding = code_page_name(code_page, &encoding_obj);
7623 if (encoding == NULL)
7624 return -1;
7625
7626 if (errors == NULL || strcmp(errors, "strict") == 0) {
7627 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7628 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007629 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007630 if (exc != NULL) {
7631 PyCodec_StrictErrors(exc);
7632 Py_DECREF(exc);
7633 }
7634 Py_XDECREF(encoding_obj);
7635 return -1;
7636 }
7637
7638 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7639 pusedDefaultChar = &usedDefaultChar;
7640 else
7641 pusedDefaultChar = NULL;
7642
7643 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7644 PyErr_NoMemory();
7645 goto error;
7646 }
7647 outsize = insize * Py_ARRAY_LENGTH(buffer);
7648
7649 if (*outbytes == NULL) {
7650 /* Create string object */
7651 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7652 if (*outbytes == NULL)
7653 goto error;
7654 out = PyBytes_AS_STRING(*outbytes);
7655 }
7656 else {
7657 /* Extend string object */
7658 Py_ssize_t n = PyBytes_Size(*outbytes);
7659 if (n > PY_SSIZE_T_MAX - outsize) {
7660 PyErr_NoMemory();
7661 goto error;
7662 }
7663 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7664 goto error;
7665 out = PyBytes_AS_STRING(*outbytes) + n;
7666 }
7667
7668 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007669 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007670 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007671 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7672 wchar_t chars[2];
7673 int charsize;
7674 if (ch < 0x10000) {
7675 chars[0] = (wchar_t)ch;
7676 charsize = 1;
7677 }
7678 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007679 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7680 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007681 charsize = 2;
7682 }
7683
Victor Stinner3a50e702011-10-18 21:21:00 +02007684 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007685 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007686 buffer, Py_ARRAY_LENGTH(buffer),
7687 NULL, pusedDefaultChar);
7688 if (outsize > 0) {
7689 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7690 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007691 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007692 memcpy(out, buffer, outsize);
7693 out += outsize;
7694 continue;
7695 }
7696 }
7697 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7698 PyErr_SetFromWindowsErr(0);
7699 goto error;
7700 }
7701
Victor Stinner3a50e702011-10-18 21:21:00 +02007702 rep = unicode_encode_call_errorhandler(
7703 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007704 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007705 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007706 if (rep == NULL)
7707 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007708 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007709
7710 if (PyBytes_Check(rep)) {
7711 outsize = PyBytes_GET_SIZE(rep);
7712 if (outsize != 1) {
7713 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7714 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7715 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7716 Py_DECREF(rep);
7717 goto error;
7718 }
7719 out = PyBytes_AS_STRING(*outbytes) + offset;
7720 }
7721 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7722 out += outsize;
7723 }
7724 else {
7725 Py_ssize_t i;
7726 enum PyUnicode_Kind kind;
7727 void *data;
7728
Benjamin Petersonbac79492012-01-14 13:34:47 -05007729 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007730 Py_DECREF(rep);
7731 goto error;
7732 }
7733
7734 outsize = PyUnicode_GET_LENGTH(rep);
7735 if (outsize != 1) {
7736 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7737 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7738 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7739 Py_DECREF(rep);
7740 goto error;
7741 }
7742 out = PyBytes_AS_STRING(*outbytes) + offset;
7743 }
7744 kind = PyUnicode_KIND(rep);
7745 data = PyUnicode_DATA(rep);
7746 for (i=0; i < outsize; i++) {
7747 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7748 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007749 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007750 encoding, unicode,
7751 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007752 "unable to encode error handler result to ASCII");
7753 Py_DECREF(rep);
7754 goto error;
7755 }
7756 *out = (unsigned char)ch;
7757 out++;
7758 }
7759 }
7760 Py_DECREF(rep);
7761 }
7762 /* write a NUL byte */
7763 *out = 0;
7764 outsize = out - PyBytes_AS_STRING(*outbytes);
7765 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7766 if (_PyBytes_Resize(outbytes, outsize) < 0)
7767 goto error;
7768 ret = 0;
7769
7770error:
7771 Py_XDECREF(encoding_obj);
7772 Py_XDECREF(errorHandler);
7773 Py_XDECREF(exc);
7774 return ret;
7775}
7776
Victor Stinner3a50e702011-10-18 21:21:00 +02007777static PyObject *
7778encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007779 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007780 const char *errors)
7781{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007782 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007783 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007784 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007785 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007786
Victor Stinner29dacf22015-01-26 16:41:32 +01007787 if (!PyUnicode_Check(unicode)) {
7788 PyErr_BadArgument();
7789 return NULL;
7790 }
7791
Benjamin Petersonbac79492012-01-14 13:34:47 -05007792 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007793 return NULL;
7794 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007795
Victor Stinner3a50e702011-10-18 21:21:00 +02007796 if (code_page < 0) {
7797 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7798 return NULL;
7799 }
7800
Martin v. Löwis3d325192011-11-04 18:23:06 +01007801 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007802 return PyBytes_FromStringAndSize(NULL, 0);
7803
Victor Stinner7581cef2011-11-03 22:32:33 +01007804 offset = 0;
7805 do
7806 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007807#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007808 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007809 chunks. */
7810 if (len > INT_MAX/2) {
7811 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007812 done = 0;
7813 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007814 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007815#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007816 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007817 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007818 done = 1;
7819 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007820
Victor Stinner76a31a62011-11-04 00:05:13 +01007821 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007822 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007823 errors);
7824 if (ret == -2)
7825 ret = encode_code_page_errors(code_page, &outbytes,
7826 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007827 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007828 if (ret < 0) {
7829 Py_XDECREF(outbytes);
7830 return NULL;
7831 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007832
Victor Stinner7581cef2011-11-03 22:32:33 +01007833 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007834 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007835 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007836
Victor Stinner3a50e702011-10-18 21:21:00 +02007837 return outbytes;
7838}
7839
7840PyObject *
7841PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7842 Py_ssize_t size,
7843 const char *errors)
7844{
Victor Stinner7581cef2011-11-03 22:32:33 +01007845 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007846 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007847 if (unicode == NULL)
7848 return NULL;
7849 res = encode_code_page(CP_ACP, unicode, errors);
7850 Py_DECREF(unicode);
7851 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007852}
7853
7854PyObject *
7855PyUnicode_EncodeCodePage(int code_page,
7856 PyObject *unicode,
7857 const char *errors)
7858{
Victor Stinner7581cef2011-11-03 22:32:33 +01007859 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007860}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007861
Alexander Belopolsky40018472011-02-26 01:02:56 +00007862PyObject *
7863PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007864{
Victor Stinner7581cef2011-11-03 22:32:33 +01007865 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007866}
7867
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007868#undef NEED_RETRY
7869
Steve Dowercc16be82016-09-08 10:35:16 -07007870#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007871
Guido van Rossumd57fd912000-03-10 22:53:23 +00007872/* --- Character Mapping Codec -------------------------------------------- */
7873
Victor Stinnerfb161b12013-04-18 01:44:27 +02007874static int
7875charmap_decode_string(const char *s,
7876 Py_ssize_t size,
7877 PyObject *mapping,
7878 const char *errors,
7879 _PyUnicodeWriter *writer)
7880{
7881 const char *starts = s;
7882 const char *e;
7883 Py_ssize_t startinpos, endinpos;
7884 PyObject *errorHandler = NULL, *exc = NULL;
7885 Py_ssize_t maplen;
7886 enum PyUnicode_Kind mapkind;
7887 void *mapdata;
7888 Py_UCS4 x;
7889 unsigned char ch;
7890
7891 if (PyUnicode_READY(mapping) == -1)
7892 return -1;
7893
7894 maplen = PyUnicode_GET_LENGTH(mapping);
7895 mapdata = PyUnicode_DATA(mapping);
7896 mapkind = PyUnicode_KIND(mapping);
7897
7898 e = s + size;
7899
7900 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7901 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7902 * is disabled in encoding aliases, latin1 is preferred because
7903 * its implementation is faster. */
7904 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7905 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7906 Py_UCS4 maxchar = writer->maxchar;
7907
7908 assert (writer->kind == PyUnicode_1BYTE_KIND);
7909 while (s < e) {
7910 ch = *s;
7911 x = mapdata_ucs1[ch];
7912 if (x > maxchar) {
7913 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7914 goto onError;
7915 maxchar = writer->maxchar;
7916 outdata = (Py_UCS1 *)writer->data;
7917 }
7918 outdata[writer->pos] = x;
7919 writer->pos++;
7920 ++s;
7921 }
7922 return 0;
7923 }
7924
7925 while (s < e) {
7926 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7927 enum PyUnicode_Kind outkind = writer->kind;
7928 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7929 if (outkind == PyUnicode_1BYTE_KIND) {
7930 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7931 Py_UCS4 maxchar = writer->maxchar;
7932 while (s < e) {
7933 ch = *s;
7934 x = mapdata_ucs2[ch];
7935 if (x > maxchar)
7936 goto Error;
7937 outdata[writer->pos] = x;
7938 writer->pos++;
7939 ++s;
7940 }
7941 break;
7942 }
7943 else if (outkind == PyUnicode_2BYTE_KIND) {
7944 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7945 while (s < e) {
7946 ch = *s;
7947 x = mapdata_ucs2[ch];
7948 if (x == 0xFFFE)
7949 goto Error;
7950 outdata[writer->pos] = x;
7951 writer->pos++;
7952 ++s;
7953 }
7954 break;
7955 }
7956 }
7957 ch = *s;
7958
7959 if (ch < maplen)
7960 x = PyUnicode_READ(mapkind, mapdata, ch);
7961 else
7962 x = 0xfffe; /* invalid value */
7963Error:
7964 if (x == 0xfffe)
7965 {
7966 /* undefined mapping */
7967 startinpos = s-starts;
7968 endinpos = startinpos+1;
7969 if (unicode_decode_call_errorhandler_writer(
7970 errors, &errorHandler,
7971 "charmap", "character maps to <undefined>",
7972 &starts, &e, &startinpos, &endinpos, &exc, &s,
7973 writer)) {
7974 goto onError;
7975 }
7976 continue;
7977 }
7978
7979 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7980 goto onError;
7981 ++s;
7982 }
7983 Py_XDECREF(errorHandler);
7984 Py_XDECREF(exc);
7985 return 0;
7986
7987onError:
7988 Py_XDECREF(errorHandler);
7989 Py_XDECREF(exc);
7990 return -1;
7991}
7992
7993static int
7994charmap_decode_mapping(const char *s,
7995 Py_ssize_t size,
7996 PyObject *mapping,
7997 const char *errors,
7998 _PyUnicodeWriter *writer)
7999{
8000 const char *starts = s;
8001 const char *e;
8002 Py_ssize_t startinpos, endinpos;
8003 PyObject *errorHandler = NULL, *exc = NULL;
8004 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02008005 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008006
8007 e = s + size;
8008
8009 while (s < e) {
8010 ch = *s;
8011
8012 /* Get mapping (char ordinal -> integer, Unicode char or None) */
8013 key = PyLong_FromLong((long)ch);
8014 if (key == NULL)
8015 goto onError;
8016
8017 item = PyObject_GetItem(mapping, key);
8018 Py_DECREF(key);
8019 if (item == NULL) {
8020 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8021 /* No mapping found means: mapping is undefined. */
8022 PyErr_Clear();
8023 goto Undefined;
8024 } else
8025 goto onError;
8026 }
8027
8028 /* Apply mapping */
8029 if (item == Py_None)
8030 goto Undefined;
8031 if (PyLong_Check(item)) {
8032 long value = PyLong_AS_LONG(item);
8033 if (value == 0xFFFE)
8034 goto Undefined;
8035 if (value < 0 || value > MAX_UNICODE) {
8036 PyErr_Format(PyExc_TypeError,
8037 "character mapping must be in range(0x%lx)",
8038 (unsigned long)MAX_UNICODE + 1);
8039 goto onError;
8040 }
8041
8042 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8043 goto onError;
8044 }
8045 else if (PyUnicode_Check(item)) {
8046 if (PyUnicode_READY(item) == -1)
8047 goto onError;
8048 if (PyUnicode_GET_LENGTH(item) == 1) {
8049 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8050 if (value == 0xFFFE)
8051 goto Undefined;
8052 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8053 goto onError;
8054 }
8055 else {
8056 writer->overallocate = 1;
8057 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8058 goto onError;
8059 }
8060 }
8061 else {
8062 /* wrong return value */
8063 PyErr_SetString(PyExc_TypeError,
8064 "character mapping must return integer, None or str");
8065 goto onError;
8066 }
8067 Py_CLEAR(item);
8068 ++s;
8069 continue;
8070
8071Undefined:
8072 /* undefined mapping */
8073 Py_CLEAR(item);
8074 startinpos = s-starts;
8075 endinpos = startinpos+1;
8076 if (unicode_decode_call_errorhandler_writer(
8077 errors, &errorHandler,
8078 "charmap", "character maps to <undefined>",
8079 &starts, &e, &startinpos, &endinpos, &exc, &s,
8080 writer)) {
8081 goto onError;
8082 }
8083 }
8084 Py_XDECREF(errorHandler);
8085 Py_XDECREF(exc);
8086 return 0;
8087
8088onError:
8089 Py_XDECREF(item);
8090 Py_XDECREF(errorHandler);
8091 Py_XDECREF(exc);
8092 return -1;
8093}
8094
Alexander Belopolsky40018472011-02-26 01:02:56 +00008095PyObject *
8096PyUnicode_DecodeCharmap(const char *s,
8097 Py_ssize_t size,
8098 PyObject *mapping,
8099 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008100{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008101 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008102
Guido van Rossumd57fd912000-03-10 22:53:23 +00008103 /* Default to Latin-1 */
8104 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008106
Guido van Rossumd57fd912000-03-10 22:53:23 +00008107 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008108 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008109 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008110 writer.min_length = size;
8111 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008112 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008113
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008114 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008115 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8116 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008117 }
8118 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008119 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8120 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008122 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008123
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008125 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 return NULL;
8127}
8128
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008129/* Charmap encoding: the lookup table */
8130
Alexander Belopolsky40018472011-02-26 01:02:56 +00008131struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 PyObject_HEAD
8133 unsigned char level1[32];
8134 int count2, count3;
8135 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136};
8137
8138static PyObject*
8139encoding_map_size(PyObject *obj, PyObject* args)
8140{
8141 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008142 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144}
8145
8146static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 PyDoc_STR("Return the size (in bytes) of this object") },
8149 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008150};
8151
8152static void
8153encoding_map_dealloc(PyObject* o)
8154{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008155 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156}
8157
8158static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008159 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 "EncodingMap", /*tp_name*/
8161 sizeof(struct encoding_map), /*tp_basicsize*/
8162 0, /*tp_itemsize*/
8163 /* methods */
8164 encoding_map_dealloc, /*tp_dealloc*/
8165 0, /*tp_print*/
8166 0, /*tp_getattr*/
8167 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008168 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 0, /*tp_repr*/
8170 0, /*tp_as_number*/
8171 0, /*tp_as_sequence*/
8172 0, /*tp_as_mapping*/
8173 0, /*tp_hash*/
8174 0, /*tp_call*/
8175 0, /*tp_str*/
8176 0, /*tp_getattro*/
8177 0, /*tp_setattro*/
8178 0, /*tp_as_buffer*/
8179 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8180 0, /*tp_doc*/
8181 0, /*tp_traverse*/
8182 0, /*tp_clear*/
8183 0, /*tp_richcompare*/
8184 0, /*tp_weaklistoffset*/
8185 0, /*tp_iter*/
8186 0, /*tp_iternext*/
8187 encoding_map_methods, /*tp_methods*/
8188 0, /*tp_members*/
8189 0, /*tp_getset*/
8190 0, /*tp_base*/
8191 0, /*tp_dict*/
8192 0, /*tp_descr_get*/
8193 0, /*tp_descr_set*/
8194 0, /*tp_dictoffset*/
8195 0, /*tp_init*/
8196 0, /*tp_alloc*/
8197 0, /*tp_new*/
8198 0, /*tp_free*/
8199 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008200};
8201
8202PyObject*
8203PyUnicode_BuildEncodingMap(PyObject* string)
8204{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 PyObject *result;
8206 struct encoding_map *mresult;
8207 int i;
8208 int need_dict = 0;
8209 unsigned char level1[32];
8210 unsigned char level2[512];
8211 unsigned char *mlevel1, *mlevel2, *mlevel3;
8212 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008213 int kind;
8214 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008215 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008216 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008217
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008218 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008219 PyErr_BadArgument();
8220 return NULL;
8221 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008222 kind = PyUnicode_KIND(string);
8223 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008224 length = PyUnicode_GET_LENGTH(string);
8225 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008226 memset(level1, 0xFF, sizeof level1);
8227 memset(level2, 0xFF, sizeof level2);
8228
8229 /* If there isn't a one-to-one mapping of NULL to \0,
8230 or if there are non-BMP characters, we need to use
8231 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008232 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008233 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008234 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008235 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008236 ch = PyUnicode_READ(kind, data, i);
8237 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008238 need_dict = 1;
8239 break;
8240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008241 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008242 /* unmapped character */
8243 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008244 l1 = ch >> 11;
8245 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008246 if (level1[l1] == 0xFF)
8247 level1[l1] = count2++;
8248 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008249 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008250 }
8251
8252 if (count2 >= 0xFF || count3 >= 0xFF)
8253 need_dict = 1;
8254
8255 if (need_dict) {
8256 PyObject *result = PyDict_New();
8257 PyObject *key, *value;
8258 if (!result)
8259 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008260 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008261 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008262 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263 if (!key || !value)
8264 goto failed1;
8265 if (PyDict_SetItem(result, key, value) == -1)
8266 goto failed1;
8267 Py_DECREF(key);
8268 Py_DECREF(value);
8269 }
8270 return result;
8271 failed1:
8272 Py_XDECREF(key);
8273 Py_XDECREF(value);
8274 Py_DECREF(result);
8275 return NULL;
8276 }
8277
8278 /* Create a three-level trie */
8279 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8280 16*count2 + 128*count3 - 1);
8281 if (!result)
8282 return PyErr_NoMemory();
8283 PyObject_Init(result, &EncodingMapType);
8284 mresult = (struct encoding_map*)result;
8285 mresult->count2 = count2;
8286 mresult->count3 = count3;
8287 mlevel1 = mresult->level1;
8288 mlevel2 = mresult->level23;
8289 mlevel3 = mresult->level23 + 16*count2;
8290 memcpy(mlevel1, level1, 32);
8291 memset(mlevel2, 0xFF, 16*count2);
8292 memset(mlevel3, 0, 128*count3);
8293 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008294 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008295 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008296 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8297 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008298 /* unmapped character */
8299 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008300 o1 = ch>>11;
8301 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008302 i2 = 16*mlevel1[o1] + o2;
8303 if (mlevel2[i2] == 0xFF)
8304 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008305 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008306 i3 = 128*mlevel2[i2] + o3;
8307 mlevel3[i3] = i;
8308 }
8309 return result;
8310}
8311
8312static int
Victor Stinner22168992011-11-20 17:09:18 +01008313encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008314{
8315 struct encoding_map *map = (struct encoding_map*)mapping;
8316 int l1 = c>>11;
8317 int l2 = (c>>7) & 0xF;
8318 int l3 = c & 0x7F;
8319 int i;
8320
Victor Stinner22168992011-11-20 17:09:18 +01008321 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008323 if (c == 0)
8324 return 0;
8325 /* level 1*/
8326 i = map->level1[l1];
8327 if (i == 0xFF) {
8328 return -1;
8329 }
8330 /* level 2*/
8331 i = map->level23[16*i+l2];
8332 if (i == 0xFF) {
8333 return -1;
8334 }
8335 /* level 3 */
8336 i = map->level23[16*map->count2 + 128*i + l3];
8337 if (i == 0) {
8338 return -1;
8339 }
8340 return i;
8341}
8342
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343/* Lookup the character ch in the mapping. If the character
8344 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008345 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008346static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008347charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348{
Christian Heimes217cfd12007-12-02 14:31:20 +00008349 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350 PyObject *x;
8351
8352 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 x = PyObject_GetItem(mapping, w);
8355 Py_DECREF(w);
8356 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8358 /* No mapping found means: mapping is undefined. */
8359 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008360 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 } else
8362 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008363 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008364 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008366 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 long value = PyLong_AS_LONG(x);
8368 if (value < 0 || value > 255) {
8369 PyErr_SetString(PyExc_TypeError,
8370 "character mapping must be in range(256)");
8371 Py_DECREF(x);
8372 return NULL;
8373 }
8374 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008375 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008376 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 /* wrong return value */
8380 PyErr_Format(PyExc_TypeError,
8381 "character mapping must return integer, bytes or None, not %.400s",
8382 x->ob_type->tp_name);
8383 Py_DECREF(x);
8384 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008385 }
8386}
8387
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008388static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008389charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008390{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008391 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8392 /* exponentially overallocate to minimize reallocations */
8393 if (requiredsize < 2*outsize)
8394 requiredsize = 2*outsize;
8395 if (_PyBytes_Resize(outobj, requiredsize))
8396 return -1;
8397 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008398}
8399
Benjamin Peterson14339b62009-01-31 16:36:08 +00008400typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008402} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008404 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405 space is available. Return a new reference to the object that
8406 was put in the output buffer, or Py_None, if the mapping was undefined
8407 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008408 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008409static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008410charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008411 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008413 PyObject *rep;
8414 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008415 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416
Christian Heimes90aa7642007-12-19 02:45:37 +00008417 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008418 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008420 if (res == -1)
8421 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 if (outsize<requiredsize)
8423 if (charmapencode_resize(outobj, outpos, requiredsize))
8424 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008425 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 outstart[(*outpos)++] = (char)res;
8427 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008428 }
8429
8430 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008433 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 Py_DECREF(rep);
8435 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008436 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 if (PyLong_Check(rep)) {
8438 Py_ssize_t requiredsize = *outpos+1;
8439 if (outsize<requiredsize)
8440 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8441 Py_DECREF(rep);
8442 return enc_EXCEPTION;
8443 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008444 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008446 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 else {
8448 const char *repchars = PyBytes_AS_STRING(rep);
8449 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8450 Py_ssize_t requiredsize = *outpos+repsize;
8451 if (outsize<requiredsize)
8452 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8453 Py_DECREF(rep);
8454 return enc_EXCEPTION;
8455 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008456 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 memcpy(outstart + *outpos, repchars, repsize);
8458 *outpos += repsize;
8459 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008461 Py_DECREF(rep);
8462 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463}
8464
8465/* handle an error in PyUnicode_EncodeCharmap
8466 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008467static int
8468charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008469 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008471 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008472 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473{
8474 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008475 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008476 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008477 enum PyUnicode_Kind kind;
8478 void *data;
8479 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008481 Py_ssize_t collstartpos = *inpos;
8482 Py_ssize_t collendpos = *inpos+1;
8483 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008484 const char *encoding = "charmap";
8485 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008486 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008487 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008488 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489
Benjamin Petersonbac79492012-01-14 13:34:47 -05008490 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008491 return -1;
8492 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 /* find all unencodable characters */
8494 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008495 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008496 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008497 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008498 val = encoding_map_lookup(ch, mapping);
8499 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 break;
8501 ++collendpos;
8502 continue;
8503 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008504
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8506 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 if (rep==NULL)
8508 return -1;
8509 else if (rep!=Py_None) {
8510 Py_DECREF(rep);
8511 break;
8512 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008513 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008514 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 }
8516 /* cache callback name lookup
8517 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008518 if (*error_handler == _Py_ERROR_UNKNOWN)
8519 *error_handler = get_error_handler(errors);
8520
8521 switch (*error_handler) {
8522 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008523 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008524 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008525
8526 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008527 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 x = charmapencode_output('?', mapping, res, respos);
8529 if (x==enc_EXCEPTION) {
8530 return -1;
8531 }
8532 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008533 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return -1;
8535 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008536 }
8537 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008538 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008539 *inpos = collendpos;
8540 break;
Victor Stinner50149202015-09-22 00:26:54 +02008541
8542 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008543 /* generate replacement (temporarily (mis)uses p) */
8544 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 char buffer[2+29+1+1];
8546 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008547 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 for (cp = buffer; *cp; ++cp) {
8549 x = charmapencode_output(*cp, mapping, res, respos);
8550 if (x==enc_EXCEPTION)
8551 return -1;
8552 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008553 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 return -1;
8555 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008556 }
8557 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008558 *inpos = collendpos;
8559 break;
Victor Stinner50149202015-09-22 00:26:54 +02008560
Benjamin Peterson14339b62009-01-31 16:36:08 +00008561 default:
Victor Stinner50149202015-09-22 00:26:54 +02008562 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008563 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008565 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008567 if (PyBytes_Check(repunicode)) {
8568 /* Directly copy bytes result to output. */
8569 Py_ssize_t outsize = PyBytes_Size(*res);
8570 Py_ssize_t requiredsize;
8571 repsize = PyBytes_Size(repunicode);
8572 requiredsize = *respos + repsize;
8573 if (requiredsize > outsize)
8574 /* Make room for all additional bytes. */
8575 if (charmapencode_resize(res, respos, requiredsize)) {
8576 Py_DECREF(repunicode);
8577 return -1;
8578 }
8579 memcpy(PyBytes_AsString(*res) + *respos,
8580 PyBytes_AsString(repunicode), repsize);
8581 *respos += repsize;
8582 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008583 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008584 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008585 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008586 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008587 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008588 Py_DECREF(repunicode);
8589 return -1;
8590 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008591 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008592 data = PyUnicode_DATA(repunicode);
8593 kind = PyUnicode_KIND(repunicode);
8594 for (index = 0; index < repsize; index++) {
8595 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8596 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008598 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 return -1;
8600 }
8601 else if (x==enc_FAILED) {
8602 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008603 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 return -1;
8605 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008606 }
8607 *inpos = newpos;
8608 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008609 }
8610 return 0;
8611}
8612
Alexander Belopolsky40018472011-02-26 01:02:56 +00008613PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008614_PyUnicode_EncodeCharmap(PyObject *unicode,
8615 PyObject *mapping,
8616 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008617{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 /* output object */
8619 PyObject *res = NULL;
8620 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008621 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008622 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008624 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008625 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008627 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008628 void *data;
8629 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008630
Benjamin Petersonbac79492012-01-14 13:34:47 -05008631 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008632 return NULL;
8633 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008634 data = PyUnicode_DATA(unicode);
8635 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008636
Guido van Rossumd57fd912000-03-10 22:53:23 +00008637 /* Default to Latin-1 */
8638 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008639 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008640
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 /* allocate enough for a simple encoding without
8642 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008643 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 if (res == NULL)
8645 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008646 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008650 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008652 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 if (x==enc_EXCEPTION) /* error */
8654 goto onError;
8655 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008656 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008658 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008659 &res, &respos)) {
8660 goto onError;
8661 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008662 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 else
8664 /* done with this character => adjust input position */
8665 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008666 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008667
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008668 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008669 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008670 if (_PyBytes_Resize(&res, respos) < 0)
8671 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008672
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008673 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008674 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 return res;
8676
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678 Py_XDECREF(res);
8679 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008680 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008681 return NULL;
8682}
8683
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008684/* Deprecated */
8685PyObject *
8686PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8687 Py_ssize_t size,
8688 PyObject *mapping,
8689 const char *errors)
8690{
8691 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008692 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008693 if (unicode == NULL)
8694 return NULL;
8695 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8696 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008697 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008698}
8699
Alexander Belopolsky40018472011-02-26 01:02:56 +00008700PyObject *
8701PyUnicode_AsCharmapString(PyObject *unicode,
8702 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008703{
8704 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 PyErr_BadArgument();
8706 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008708 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008709}
8710
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008712static void
8713make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008715 Py_ssize_t startpos, Py_ssize_t endpos,
8716 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008717{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008718 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008719 *exceptionObject = _PyUnicodeTranslateError_Create(
8720 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008721 }
8722 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8724 goto onError;
8725 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8726 goto onError;
8727 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8728 goto onError;
8729 return;
8730 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008731 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008732 }
8733}
8734
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008735/* error handling callback helper:
8736 build arguments, call the callback and check the arguments,
8737 put the result into newpos and return the replacement string, which
8738 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008739static PyObject *
8740unicode_translate_call_errorhandler(const char *errors,
8741 PyObject **errorHandler,
8742 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008744 Py_ssize_t startpos, Py_ssize_t endpos,
8745 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008746{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008747 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008749 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750 PyObject *restuple;
8751 PyObject *resunicode;
8752
8753 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008755 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008757 }
8758
8759 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008760 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008761 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008764 restuple = PyObject_CallFunctionObjArgs(
8765 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008766 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008768 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008769 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 Py_DECREF(restuple);
8771 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008772 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008773 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 &resunicode, &i_newpos)) {
8775 Py_DECREF(restuple);
8776 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008777 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008778 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008780 else
8781 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008783 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008784 Py_DECREF(restuple);
8785 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008786 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008787 Py_INCREF(resunicode);
8788 Py_DECREF(restuple);
8789 return resunicode;
8790}
8791
8792/* Lookup the character ch in the mapping and put the result in result,
8793 which must be decrefed by the caller.
8794 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008795static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008796charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008797{
Christian Heimes217cfd12007-12-02 14:31:20 +00008798 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008799 PyObject *x;
8800
8801 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008802 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008803 x = PyObject_GetItem(mapping, w);
8804 Py_DECREF(w);
8805 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008806 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8807 /* No mapping found means: use 1:1 mapping. */
8808 PyErr_Clear();
8809 *result = NULL;
8810 return 0;
8811 } else
8812 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008813 }
8814 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008815 *result = x;
8816 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008817 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008818 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008819 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008820 if (value < 0 || value > MAX_UNICODE) {
8821 PyErr_Format(PyExc_ValueError,
8822 "character mapping must be in range(0x%x)",
8823 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008824 Py_DECREF(x);
8825 return -1;
8826 }
8827 *result = x;
8828 return 0;
8829 }
8830 else if (PyUnicode_Check(x)) {
8831 *result = x;
8832 return 0;
8833 }
8834 else {
8835 /* wrong return value */
8836 PyErr_SetString(PyExc_TypeError,
8837 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008838 Py_DECREF(x);
8839 return -1;
8840 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008841}
Victor Stinner1194ea02014-04-04 19:37:40 +02008842
8843/* lookup the character, write the result into the writer.
8844 Return 1 if the result was written into the writer, return 0 if the mapping
8845 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008846static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008847charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8848 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008849{
Victor Stinner1194ea02014-04-04 19:37:40 +02008850 PyObject *item;
8851
8852 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008853 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008854
8855 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008857 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008858 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008859 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008860 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008861 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008862
8863 if (item == Py_None) {
8864 Py_DECREF(item);
8865 return 0;
8866 }
8867
8868 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008869 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8870 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8871 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008872 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8873 Py_DECREF(item);
8874 return -1;
8875 }
8876 Py_DECREF(item);
8877 return 1;
8878 }
8879
8880 if (!PyUnicode_Check(item)) {
8881 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008882 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008883 }
8884
8885 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8886 Py_DECREF(item);
8887 return -1;
8888 }
8889
8890 Py_DECREF(item);
8891 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008892}
8893
Victor Stinner89a76ab2014-04-05 11:44:04 +02008894static int
8895unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8896 Py_UCS1 *translate)
8897{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008898 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008899 int ret = 0;
8900
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901 if (charmaptranslate_lookup(ch, mapping, &item)) {
8902 return -1;
8903 }
8904
8905 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008906 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008907 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008908 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008909 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008910 /* not found => default to 1:1 mapping */
8911 translate[ch] = ch;
8912 return 1;
8913 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008914 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008915 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008916 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8917 used it */
8918 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008919 /* invalid character or character outside ASCII:
8920 skip the fast translate */
8921 goto exit;
8922 }
8923 translate[ch] = (Py_UCS1)replace;
8924 }
8925 else if (PyUnicode_Check(item)) {
8926 Py_UCS4 replace;
8927
8928 if (PyUnicode_READY(item) == -1) {
8929 Py_DECREF(item);
8930 return -1;
8931 }
8932 if (PyUnicode_GET_LENGTH(item) != 1)
8933 goto exit;
8934
8935 replace = PyUnicode_READ_CHAR(item, 0);
8936 if (replace > 127)
8937 goto exit;
8938 translate[ch] = (Py_UCS1)replace;
8939 }
8940 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008941 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008942 goto exit;
8943 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008944 ret = 1;
8945
Benjamin Peterson1365de72014-04-07 20:15:41 -04008946 exit:
8947 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008948 return ret;
8949}
8950
8951/* Fast path for ascii => ascii translation. Return 1 if the whole string
8952 was translated into writer, return 0 if the input string was partially
8953 translated into writer, raise an exception and return -1 on error. */
8954static int
8955unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008956 _PyUnicodeWriter *writer, int ignore,
8957 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008958{
Victor Stinner872b2912014-04-05 14:27:07 +02008959 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008960 Py_ssize_t len;
8961 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008962 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008963
Victor Stinner89a76ab2014-04-05 11:44:04 +02008964 len = PyUnicode_GET_LENGTH(input);
8965
Victor Stinner872b2912014-04-05 14:27:07 +02008966 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008967
8968 in = PyUnicode_1BYTE_DATA(input);
8969 end = in + len;
8970
8971 assert(PyUnicode_IS_ASCII(writer->buffer));
8972 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8973 out = PyUnicode_1BYTE_DATA(writer->buffer);
8974
Victor Stinner872b2912014-04-05 14:27:07 +02008975 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008976 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008977 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008978 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008979 int translate = unicode_fast_translate_lookup(mapping, ch,
8980 ascii_table);
8981 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008982 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008983 if (translate == 0)
8984 goto exit;
8985 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008986 }
Victor Stinner872b2912014-04-05 14:27:07 +02008987 if (ch2 == 0xfe) {
8988 if (ignore)
8989 continue;
8990 goto exit;
8991 }
8992 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008993 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008994 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008995 }
Victor Stinner872b2912014-04-05 14:27:07 +02008996 res = 1;
8997
8998exit:
8999 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009000 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02009001 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009002}
9003
Victor Stinner3222da22015-10-01 22:07:32 +02009004static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009005_PyUnicode_TranslateCharmap(PyObject *input,
9006 PyObject *mapping,
9007 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02009010 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 Py_ssize_t size, i;
9012 int kind;
9013 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02009014 _PyUnicodeWriter writer;
9015 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02009016 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009017 PyObject *errorHandler = NULL;
9018 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009019 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009020 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009021
Guido van Rossumd57fd912000-03-10 22:53:23 +00009022 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009023 PyErr_BadArgument();
9024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027 if (PyUnicode_READY(input) == -1)
9028 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009029 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030 kind = PyUnicode_KIND(input);
9031 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009033 if (size == 0)
9034 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009036 /* allocate enough for a simple 1:1 translation without
9037 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009038 _PyUnicodeWriter_Init(&writer);
9039 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009040 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009041
Victor Stinner872b2912014-04-05 14:27:07 +02009042 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9043
Victor Stinner33798672016-03-01 21:59:58 +01009044 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009045 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009046 if (PyUnicode_IS_ASCII(input)) {
9047 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9048 if (res < 0) {
9049 _PyUnicodeWriter_Dealloc(&writer);
9050 return NULL;
9051 }
9052 if (res == 1)
9053 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009054 }
Victor Stinner33798672016-03-01 21:59:58 +01009055 else {
9056 i = 0;
9057 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009060 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009061 int translate;
9062 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9063 Py_ssize_t newpos;
9064 /* startpos for collecting untranslatable chars */
9065 Py_ssize_t collstart;
9066 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009067 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009068
Victor Stinner1194ea02014-04-04 19:37:40 +02009069 ch = PyUnicode_READ(kind, data, i);
9070 translate = charmaptranslate_output(ch, mapping, &writer);
9071 if (translate < 0)
9072 goto onError;
9073
9074 if (translate != 0) {
9075 /* it worked => adjust input pointer */
9076 ++i;
9077 continue;
9078 }
9079
9080 /* untranslatable character */
9081 collstart = i;
9082 collend = i+1;
9083
9084 /* find all untranslatable characters */
9085 while (collend < size) {
9086 PyObject *x;
9087 ch = PyUnicode_READ(kind, data, collend);
9088 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009089 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009090 Py_XDECREF(x);
9091 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009092 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009093 ++collend;
9094 }
9095
9096 if (ignore) {
9097 i = collend;
9098 }
9099 else {
9100 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9101 reason, input, &exc,
9102 collstart, collend, &newpos);
9103 if (repunicode == NULL)
9104 goto onError;
9105 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009106 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009107 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009108 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009109 Py_DECREF(repunicode);
9110 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009111 }
9112 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009113 Py_XDECREF(exc);
9114 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009115 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009116
Benjamin Peterson29060642009-01-31 22:14:21 +00009117 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009118 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009119 Py_XDECREF(exc);
9120 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009121 return NULL;
9122}
9123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124/* Deprecated. Use PyUnicode_Translate instead. */
9125PyObject *
9126PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9127 Py_ssize_t size,
9128 PyObject *mapping,
9129 const char *errors)
9130{
Christian Heimes5f520f42012-09-11 14:03:25 +02009131 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009132 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 if (!unicode)
9134 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009135 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9136 Py_DECREF(unicode);
9137 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009138}
9139
Alexander Belopolsky40018472011-02-26 01:02:56 +00009140PyObject *
9141PyUnicode_Translate(PyObject *str,
9142 PyObject *mapping,
9143 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009144{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009145 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009146 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009147 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148}
Tim Petersced69f82003-09-16 20:30:58 +00009149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009150PyObject *
9151_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9152{
9153 if (!PyUnicode_Check(unicode)) {
9154 PyErr_BadInternalCall();
9155 return NULL;
9156 }
9157 if (PyUnicode_READY(unicode) == -1)
9158 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009159 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009160 /* If the string is already ASCII, just return the same string */
9161 Py_INCREF(unicode);
9162 return unicode;
9163 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009164
9165 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9166 PyObject *result = PyUnicode_New(len, 127);
9167 if (result == NULL) {
9168 return NULL;
9169 }
9170
9171 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9172 int kind = PyUnicode_KIND(unicode);
9173 const void *data = PyUnicode_DATA(unicode);
9174 Py_ssize_t i;
9175 for (i = 0; i < len; ++i) {
9176 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9177 if (ch < 127) {
9178 out[i] = ch;
9179 }
9180 else if (Py_UNICODE_ISSPACE(ch)) {
9181 out[i] = ' ';
9182 }
9183 else {
9184 int decimal = Py_UNICODE_TODECIMAL(ch);
9185 if (decimal < 0) {
9186 out[i] = '?';
9187 _PyUnicode_LENGTH(result) = i + 1;
9188 break;
9189 }
9190 out[i] = '0' + decimal;
9191 }
9192 }
9193
9194 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195}
9196
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009197PyObject *
9198PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9199 Py_ssize_t length)
9200{
Victor Stinnerf0124502011-11-21 23:12:56 +01009201 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009202 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009203 Py_UCS4 maxchar;
9204 enum PyUnicode_Kind kind;
9205 void *data;
9206
Victor Stinner99d7ad02012-02-22 13:37:39 +01009207 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009208 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009209 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009210 if (ch > 127) {
9211 int decimal = Py_UNICODE_TODECIMAL(ch);
9212 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009213 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009214 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009215 }
9216 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009217
9218 /* Copy to a new string */
9219 decimal = PyUnicode_New(length, maxchar);
9220 if (decimal == NULL)
9221 return decimal;
9222 kind = PyUnicode_KIND(decimal);
9223 data = PyUnicode_DATA(decimal);
9224 /* Iterate over code points */
9225 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009226 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009227 if (ch > 127) {
9228 int decimal = Py_UNICODE_TODECIMAL(ch);
9229 if (decimal >= 0)
9230 ch = '0' + decimal;
9231 }
9232 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009233 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009234 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009235}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009236/* --- Decimal Encoder ---------------------------------------------------- */
9237
Alexander Belopolsky40018472011-02-26 01:02:56 +00009238int
9239PyUnicode_EncodeDecimal(Py_UNICODE *s,
9240 Py_ssize_t length,
9241 char *output,
9242 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009243{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009244 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009245 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009246 enum PyUnicode_Kind kind;
9247 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009248
9249 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009250 PyErr_BadArgument();
9251 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009252 }
9253
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009254 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009255 if (unicode == NULL)
9256 return -1;
9257
Victor Stinner42bf7752011-11-21 22:52:58 +01009258 kind = PyUnicode_KIND(unicode);
9259 data = PyUnicode_DATA(unicode);
9260
Victor Stinnerb84d7232011-11-22 01:50:07 +01009261 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009262 PyObject *exc;
9263 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009264 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009265 Py_ssize_t startpos;
9266
9267 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009268
Benjamin Peterson29060642009-01-31 22:14:21 +00009269 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009270 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009271 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009272 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009273 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009274 decimal = Py_UNICODE_TODECIMAL(ch);
9275 if (decimal >= 0) {
9276 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009277 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009278 continue;
9279 }
9280 if (0 < ch && ch < 256) {
9281 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009282 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009283 continue;
9284 }
Victor Stinner6345be92011-11-25 20:09:01 +01009285
Victor Stinner42bf7752011-11-21 22:52:58 +01009286 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009287 exc = NULL;
9288 raise_encode_exception(&exc, "decimal", unicode,
9289 startpos, startpos+1,
9290 "invalid decimal Unicode string");
9291 Py_XDECREF(exc);
9292 Py_DECREF(unicode);
9293 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009294 }
9295 /* 0-terminate the output string */
9296 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009297 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009298 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009299}
9300
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301/* --- Helpers ------------------------------------------------------------ */
9302
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009303/* helper macro to fixup start/end slice values */
9304#define ADJUST_INDICES(start, end, len) \
9305 if (end > len) \
9306 end = len; \
9307 else if (end < 0) { \
9308 end += len; \
9309 if (end < 0) \
9310 end = 0; \
9311 } \
9312 if (start < 0) { \
9313 start += len; \
9314 if (start < 0) \
9315 start = 0; \
9316 }
9317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009319any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009321 Py_ssize_t end,
9322 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009324 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325 void *buf1, *buf2;
9326 Py_ssize_t len1, len2, result;
9327
9328 kind1 = PyUnicode_KIND(s1);
9329 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009330 if (kind1 < kind2)
9331 return -1;
9332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 len1 = PyUnicode_GET_LENGTH(s1);
9334 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009335 ADJUST_INDICES(start, end, len1);
9336 if (end - start < len2)
9337 return -1;
9338
9339 buf1 = PyUnicode_DATA(s1);
9340 buf2 = PyUnicode_DATA(s2);
9341 if (len2 == 1) {
9342 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9343 result = findchar((const char *)buf1 + kind1*start,
9344 kind1, end - start, ch, direction);
9345 if (result == -1)
9346 return -1;
9347 else
9348 return start + result;
9349 }
9350
9351 if (kind2 != kind1) {
9352 buf2 = _PyUnicode_AsKind(s2, kind1);
9353 if (!buf2)
9354 return -2;
9355 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356
Victor Stinner794d5672011-10-10 03:21:36 +02009357 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009358 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009359 case PyUnicode_1BYTE_KIND:
9360 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9361 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9362 else
9363 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9364 break;
9365 case PyUnicode_2BYTE_KIND:
9366 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9367 break;
9368 case PyUnicode_4BYTE_KIND:
9369 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9370 break;
9371 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009372 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009373 }
9374 }
9375 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009376 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009377 case PyUnicode_1BYTE_KIND:
9378 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9379 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9380 else
9381 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9382 break;
9383 case PyUnicode_2BYTE_KIND:
9384 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9385 break;
9386 case PyUnicode_4BYTE_KIND:
9387 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9388 break;
9389 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009390 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009391 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 }
9393
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009394 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 PyMem_Free(buf2);
9396
9397 return result;
9398}
9399
9400Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009401_PyUnicode_InsertThousandsGrouping(
9402 PyObject *unicode, Py_ssize_t index,
9403 Py_ssize_t n_buffer,
9404 void *digits, Py_ssize_t n_digits,
9405 Py_ssize_t min_width,
9406 const char *grouping, PyObject *thousands_sep,
9407 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408{
Victor Stinner41a863c2012-02-24 00:37:51 +01009409 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009410 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009411 Py_ssize_t thousands_sep_len;
9412 Py_ssize_t len;
9413
9414 if (unicode != NULL) {
9415 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009416 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009417 }
9418 else {
9419 kind = PyUnicode_1BYTE_KIND;
9420 data = NULL;
9421 }
9422 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9423 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9424 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9425 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009426 if (thousands_sep_kind < kind) {
9427 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9428 if (!thousands_sep_data)
9429 return -1;
9430 }
9431 else {
9432 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9433 if (!data)
9434 return -1;
9435 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009436 }
9437
Benjamin Petersonead6b532011-12-20 17:23:42 -06009438 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009440 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009441 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009442 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009443 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009444 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009445 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009446 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009447 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009448 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009449 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009450 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009452 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009453 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009454 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009455 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009456 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009458 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009459 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009460 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009461 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009462 break;
9463 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009464 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009466 if (unicode != NULL && thousands_sep_kind != kind) {
9467 if (thousands_sep_kind < kind)
9468 PyMem_Free(thousands_sep_data);
9469 else
9470 PyMem_Free(data);
9471 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009472 if (unicode == NULL) {
9473 *maxchar = 127;
9474 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009475 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009476 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009477 }
9478 }
9479 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480}
9481
9482
Alexander Belopolsky40018472011-02-26 01:02:56 +00009483Py_ssize_t
9484PyUnicode_Count(PyObject *str,
9485 PyObject *substr,
9486 Py_ssize_t start,
9487 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009489 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009490 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 void *buf1 = NULL, *buf2 = NULL;
9492 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009493
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009494 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009495 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009496
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009497 kind1 = PyUnicode_KIND(str);
9498 kind2 = PyUnicode_KIND(substr);
9499 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009500 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009501
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009502 len1 = PyUnicode_GET_LENGTH(str);
9503 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009505 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009506 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009507
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009508 buf1 = PyUnicode_DATA(str);
9509 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009510 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009511 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009512 if (!buf2)
9513 goto onError;
9514 }
9515
9516 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009517 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009518 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009519 result = asciilib_count(
9520 ((Py_UCS1*)buf1) + start, end - start,
9521 buf2, len2, PY_SSIZE_T_MAX
9522 );
9523 else
9524 result = ucs1lib_count(
9525 ((Py_UCS1*)buf1) + start, end - start,
9526 buf2, len2, PY_SSIZE_T_MAX
9527 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 break;
9529 case PyUnicode_2BYTE_KIND:
9530 result = ucs2lib_count(
9531 ((Py_UCS2*)buf1) + start, end - start,
9532 buf2, len2, PY_SSIZE_T_MAX
9533 );
9534 break;
9535 case PyUnicode_4BYTE_KIND:
9536 result = ucs4lib_count(
9537 ((Py_UCS4*)buf1) + start, end - start,
9538 buf2, len2, PY_SSIZE_T_MAX
9539 );
9540 break;
9541 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009542 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009544
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009545 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 PyMem_Free(buf2);
9547
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009550 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 PyMem_Free(buf2);
9552 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553}
9554
Alexander Belopolsky40018472011-02-26 01:02:56 +00009555Py_ssize_t
9556PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009557 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009558 Py_ssize_t start,
9559 Py_ssize_t end,
9560 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009562 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009563 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009564
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009565 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566}
9567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568Py_ssize_t
9569PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9570 Py_ssize_t start, Py_ssize_t end,
9571 int direction)
9572{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009573 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009574 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 if (PyUnicode_READY(str) == -1)
9576 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009577 len = PyUnicode_GET_LENGTH(str);
9578 ADJUST_INDICES(start, end, len);
9579 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009580 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009582 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9583 kind, end-start, ch, direction);
9584 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009586 else
9587 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588}
9589
Alexander Belopolsky40018472011-02-26 01:02:56 +00009590static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009591tailmatch(PyObject *self,
9592 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009593 Py_ssize_t start,
9594 Py_ssize_t end,
9595 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597 int kind_self;
9598 int kind_sub;
9599 void *data_self;
9600 void *data_sub;
9601 Py_ssize_t offset;
9602 Py_ssize_t i;
9603 Py_ssize_t end_sub;
9604
9605 if (PyUnicode_READY(self) == -1 ||
9606 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009607 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009609 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9610 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009611 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009612 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009614 if (PyUnicode_GET_LENGTH(substring) == 0)
9615 return 1;
9616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 kind_self = PyUnicode_KIND(self);
9618 data_self = PyUnicode_DATA(self);
9619 kind_sub = PyUnicode_KIND(substring);
9620 data_sub = PyUnicode_DATA(substring);
9621 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9622
9623 if (direction > 0)
9624 offset = end;
9625 else
9626 offset = start;
9627
9628 if (PyUnicode_READ(kind_self, data_self, offset) ==
9629 PyUnicode_READ(kind_sub, data_sub, 0) &&
9630 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9631 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9632 /* If both are of the same kind, memcmp is sufficient */
9633 if (kind_self == kind_sub) {
9634 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009635 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009636 data_sub,
9637 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009638 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009639 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009640 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641 else {
9642 /* We do not need to compare 0 and len(substring)-1 because
9643 the if statement above ensured already that they are equal
9644 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 for (i = 1; i < end_sub; ++i) {
9646 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9647 PyUnicode_READ(kind_sub, data_sub, i))
9648 return 0;
9649 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009650 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652 }
9653
9654 return 0;
9655}
9656
Alexander Belopolsky40018472011-02-26 01:02:56 +00009657Py_ssize_t
9658PyUnicode_Tailmatch(PyObject *str,
9659 PyObject *substr,
9660 Py_ssize_t start,
9661 Py_ssize_t end,
9662 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009663{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009664 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009665 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009666
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009667 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668}
9669
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670static PyObject *
9671ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009673 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9674 char *resdata, *data = PyUnicode_DATA(self);
9675 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009676
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 res = PyUnicode_New(len, 127);
9678 if (res == NULL)
9679 return NULL;
9680 resdata = PyUnicode_DATA(res);
9681 if (lower)
9682 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009683 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009684 _Py_bytes_upper(resdata, data, len);
9685 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686}
9687
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009688static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009689handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 Py_ssize_t j;
9692 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009693 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009694 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009695
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009696 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9697
9698 where ! is a negation and \p{xxx} is a character with property xxx.
9699 */
9700 for (j = i - 1; j >= 0; j--) {
9701 c = PyUnicode_READ(kind, data, j);
9702 if (!_PyUnicode_IsCaseIgnorable(c))
9703 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009704 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009705 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9706 if (final_sigma) {
9707 for (j = i + 1; j < length; j++) {
9708 c = PyUnicode_READ(kind, data, j);
9709 if (!_PyUnicode_IsCaseIgnorable(c))
9710 break;
9711 }
9712 final_sigma = j == length || !_PyUnicode_IsCased(c);
9713 }
9714 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009715}
9716
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009717static int
9718lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9719 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009720{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009721 /* Obscure special case. */
9722 if (c == 0x3A3) {
9723 mapped[0] = handle_capital_sigma(kind, data, length, i);
9724 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009725 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009726 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009727}
9728
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009729static Py_ssize_t
9730do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009731{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009732 Py_ssize_t i, k = 0;
9733 int n_res, j;
9734 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009735
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009736 c = PyUnicode_READ(kind, data, 0);
9737 n_res = _PyUnicode_ToUpperFull(c, mapped);
9738 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009739 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009740 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009741 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742 for (i = 1; i < length; i++) {
9743 c = PyUnicode_READ(kind, data, i);
9744 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9745 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009746 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009747 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009748 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009749 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009750 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009751}
9752
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009753static Py_ssize_t
9754do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9755 Py_ssize_t i, k = 0;
9756
9757 for (i = 0; i < length; i++) {
9758 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9759 int n_res, j;
9760 if (Py_UNICODE_ISUPPER(c)) {
9761 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9762 }
9763 else if (Py_UNICODE_ISLOWER(c)) {
9764 n_res = _PyUnicode_ToUpperFull(c, mapped);
9765 }
9766 else {
9767 n_res = 1;
9768 mapped[0] = c;
9769 }
9770 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009771 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009772 res[k++] = mapped[j];
9773 }
9774 }
9775 return k;
9776}
9777
9778static Py_ssize_t
9779do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9780 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009781{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009782 Py_ssize_t i, k = 0;
9783
9784 for (i = 0; i < length; i++) {
9785 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9786 int n_res, j;
9787 if (lower)
9788 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9789 else
9790 n_res = _PyUnicode_ToUpperFull(c, mapped);
9791 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009792 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009793 res[k++] = mapped[j];
9794 }
9795 }
9796 return k;
9797}
9798
9799static Py_ssize_t
9800do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9801{
9802 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9803}
9804
9805static Py_ssize_t
9806do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9807{
9808 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9809}
9810
Benjamin Petersone51757f2012-01-12 21:10:29 -05009811static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009812do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9813{
9814 Py_ssize_t i, k = 0;
9815
9816 for (i = 0; i < length; i++) {
9817 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9818 Py_UCS4 mapped[3];
9819 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9820 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009821 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009822 res[k++] = mapped[j];
9823 }
9824 }
9825 return k;
9826}
9827
9828static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009829do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9830{
9831 Py_ssize_t i, k = 0;
9832 int previous_is_cased;
9833
9834 previous_is_cased = 0;
9835 for (i = 0; i < length; i++) {
9836 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9837 Py_UCS4 mapped[3];
9838 int n_res, j;
9839
9840 if (previous_is_cased)
9841 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9842 else
9843 n_res = _PyUnicode_ToTitleFull(c, mapped);
9844
9845 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009846 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009847 res[k++] = mapped[j];
9848 }
9849
9850 previous_is_cased = _PyUnicode_IsCased(c);
9851 }
9852 return k;
9853}
9854
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009855static PyObject *
9856case_operation(PyObject *self,
9857 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9858{
9859 PyObject *res = NULL;
9860 Py_ssize_t length, newlength = 0;
9861 int kind, outkind;
9862 void *data, *outdata;
9863 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9864
Benjamin Petersoneea48462012-01-16 14:28:50 -05009865 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009866
9867 kind = PyUnicode_KIND(self);
9868 data = PyUnicode_DATA(self);
9869 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009870 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009871 PyErr_SetString(PyExc_OverflowError, "string is too long");
9872 return NULL;
9873 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009874 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009875 if (tmp == NULL)
9876 return PyErr_NoMemory();
9877 newlength = perform(kind, data, length, tmp, &maxchar);
9878 res = PyUnicode_New(newlength, maxchar);
9879 if (res == NULL)
9880 goto leave;
9881 tmpend = tmp + newlength;
9882 outdata = PyUnicode_DATA(res);
9883 outkind = PyUnicode_KIND(res);
9884 switch (outkind) {
9885 case PyUnicode_1BYTE_KIND:
9886 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9887 break;
9888 case PyUnicode_2BYTE_KIND:
9889 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9890 break;
9891 case PyUnicode_4BYTE_KIND:
9892 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9893 break;
9894 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009895 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009896 }
9897 leave:
9898 PyMem_FREE(tmp);
9899 return res;
9900}
9901
Tim Peters8ce9f162004-08-27 01:49:32 +00009902PyObject *
9903PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009905 PyObject *res;
9906 PyObject *fseq;
9907 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009908 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009909
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009910 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009911 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009912 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009913 }
9914
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009915 /* NOTE: the following code can't call back into Python code,
9916 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009917 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009918
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009919 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009920 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009921 res = _PyUnicode_JoinArray(separator, items, seqlen);
9922 Py_DECREF(fseq);
9923 return res;
9924}
9925
9926PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009927_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009928{
9929 PyObject *res = NULL; /* the result */
9930 PyObject *sep = NULL;
9931 Py_ssize_t seplen;
9932 PyObject *item;
9933 Py_ssize_t sz, i, res_offset;
9934 Py_UCS4 maxchar;
9935 Py_UCS4 item_maxchar;
9936 int use_memcpy;
9937 unsigned char *res_data = NULL, *sep_data = NULL;
9938 PyObject *last_obj;
9939 unsigned int kind = 0;
9940
Tim Peters05eba1f2004-08-27 21:32:02 +00009941 /* If empty sequence, return u"". */
9942 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009943 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009944 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009945
Tim Peters05eba1f2004-08-27 21:32:02 +00009946 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009947 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009948 if (seqlen == 1) {
9949 if (PyUnicode_CheckExact(items[0])) {
9950 res = items[0];
9951 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009952 return res;
9953 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009954 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009955 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009956 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009957 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009958 /* Set up sep and seplen */
9959 if (separator == NULL) {
9960 /* fall back to a blank space separator */
9961 sep = PyUnicode_FromOrdinal(' ');
9962 if (!sep)
9963 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009964 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009965 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009966 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009967 else {
9968 if (!PyUnicode_Check(separator)) {
9969 PyErr_Format(PyExc_TypeError,
9970 "separator: expected str instance,"
9971 " %.80s found",
9972 Py_TYPE(separator)->tp_name);
9973 goto onError;
9974 }
9975 if (PyUnicode_READY(separator))
9976 goto onError;
9977 sep = separator;
9978 seplen = PyUnicode_GET_LENGTH(separator);
9979 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9980 /* inc refcount to keep this code path symmetric with the
9981 above case of a blank separator */
9982 Py_INCREF(sep);
9983 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009984 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009985 }
9986
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009987 /* There are at least two things to join, or else we have a subclass
9988 * of str in the sequence.
9989 * Do a pre-pass to figure out the total amount of space we'll
9990 * need (sz), and see whether all argument are strings.
9991 */
9992 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009993#ifdef Py_DEBUG
9994 use_memcpy = 0;
9995#else
9996 use_memcpy = 1;
9997#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009998 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009999 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010000 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010001 if (!PyUnicode_Check(item)) {
10002 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010003 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010004 " %.80s found",
10005 i, Py_TYPE(item)->tp_name);
10006 goto onError;
10007 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 if (PyUnicode_READY(item) == -1)
10009 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010010 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010012 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010013 if (i != 0) {
10014 add_sz += seplen;
10015 }
10016 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010017 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010018 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010019 goto onError;
10020 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010021 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010022 if (use_memcpy && last_obj != NULL) {
10023 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10024 use_memcpy = 0;
10025 }
10026 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010027 }
Tim Petersced69f82003-09-16 20:30:58 +000010028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010030 if (res == NULL)
10031 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010032
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010033 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010034#ifdef Py_DEBUG
10035 use_memcpy = 0;
10036#else
10037 if (use_memcpy) {
10038 res_data = PyUnicode_1BYTE_DATA(res);
10039 kind = PyUnicode_KIND(res);
10040 if (seplen != 0)
10041 sep_data = PyUnicode_1BYTE_DATA(sep);
10042 }
10043#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010044 if (use_memcpy) {
10045 for (i = 0; i < seqlen; ++i) {
10046 Py_ssize_t itemlen;
10047 item = items[i];
10048
10049 /* Copy item, and maybe the separator. */
10050 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010051 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010052 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010053 kind * seplen);
10054 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010055 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010056
10057 itemlen = PyUnicode_GET_LENGTH(item);
10058 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010059 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010060 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010061 kind * itemlen);
10062 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010063 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010064 }
10065 assert(res_data == PyUnicode_1BYTE_DATA(res)
10066 + kind * PyUnicode_GET_LENGTH(res));
10067 }
10068 else {
10069 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10070 Py_ssize_t itemlen;
10071 item = items[i];
10072
10073 /* Copy item, and maybe the separator. */
10074 if (i && seplen != 0) {
10075 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10076 res_offset += seplen;
10077 }
10078
10079 itemlen = PyUnicode_GET_LENGTH(item);
10080 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010081 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010082 res_offset += itemlen;
10083 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010084 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010085 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010086 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010089 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091
Benjamin Peterson29060642009-01-31 22:14:21 +000010092 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010094 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095 return NULL;
10096}
10097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098#define FILL(kind, data, value, start, length) \
10099 do { \
10100 Py_ssize_t i_ = 0; \
10101 assert(kind != PyUnicode_WCHAR_KIND); \
10102 switch ((kind)) { \
10103 case PyUnicode_1BYTE_KIND: { \
10104 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010105 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 break; \
10107 } \
10108 case PyUnicode_2BYTE_KIND: { \
10109 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10110 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10111 break; \
10112 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010113 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10115 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10116 break; \
10117 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010118 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 } \
10120 } while (0)
10121
Victor Stinnerd3f08822012-05-29 12:57:52 +020010122void
10123_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10124 Py_UCS4 fill_char)
10125{
10126 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10127 const void *data = PyUnicode_DATA(unicode);
10128 assert(PyUnicode_IS_READY(unicode));
10129 assert(unicode_modifiable(unicode));
10130 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10131 assert(start >= 0);
10132 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10133 FILL(kind, data, fill_char, start, length);
10134}
10135
Victor Stinner3fe55312012-01-04 00:33:50 +010010136Py_ssize_t
10137PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10138 Py_UCS4 fill_char)
10139{
10140 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010141
10142 if (!PyUnicode_Check(unicode)) {
10143 PyErr_BadInternalCall();
10144 return -1;
10145 }
10146 if (PyUnicode_READY(unicode) == -1)
10147 return -1;
10148 if (unicode_check_modifiable(unicode))
10149 return -1;
10150
Victor Stinnerd3f08822012-05-29 12:57:52 +020010151 if (start < 0) {
10152 PyErr_SetString(PyExc_IndexError, "string index out of range");
10153 return -1;
10154 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010155 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10156 PyErr_SetString(PyExc_ValueError,
10157 "fill character is bigger than "
10158 "the string maximum character");
10159 return -1;
10160 }
10161
10162 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10163 length = Py_MIN(maxlen, length);
10164 if (length <= 0)
10165 return 0;
10166
Victor Stinnerd3f08822012-05-29 12:57:52 +020010167 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010168 return length;
10169}
10170
Victor Stinner9310abb2011-10-05 00:59:23 +020010171static PyObject *
10172pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010173 Py_ssize_t left,
10174 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 PyObject *u;
10178 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010179 int kind;
10180 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010181
10182 if (left < 0)
10183 left = 0;
10184 if (right < 0)
10185 right = 0;
10186
Victor Stinnerc4b49542011-12-11 22:44:26 +010010187 if (left == 0 && right == 0)
10188 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10191 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010192 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10193 return NULL;
10194 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010196 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010198 if (!u)
10199 return NULL;
10200
10201 kind = PyUnicode_KIND(u);
10202 data = PyUnicode_DATA(u);
10203 if (left)
10204 FILL(kind, data, fill, 0, left);
10205 if (right)
10206 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010207 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010208 assert(_PyUnicode_CheckConsistency(u, 1));
10209 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010210}
10211
Alexander Belopolsky40018472011-02-26 01:02:56 +000010212PyObject *
10213PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010216
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010217 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010218 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010219
Benjamin Petersonead6b532011-12-20 17:23:42 -060010220 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 if (PyUnicode_IS_ASCII(string))
10223 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010224 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010225 PyUnicode_GET_LENGTH(string), keepends);
10226 else
10227 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010228 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 break;
10231 case PyUnicode_2BYTE_KIND:
10232 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010233 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 PyUnicode_GET_LENGTH(string), keepends);
10235 break;
10236 case PyUnicode_4BYTE_KIND:
10237 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 PyUnicode_GET_LENGTH(string), keepends);
10240 break;
10241 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010242 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010244 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010245}
10246
Alexander Belopolsky40018472011-02-26 01:02:56 +000010247static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010248split(PyObject *self,
10249 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010250 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010251{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010252 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 void *buf1, *buf2;
10254 Py_ssize_t len1, len2;
10255 PyObject* out;
10256
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010258 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 if (PyUnicode_READY(self) == -1)
10261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010264 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010266 if (PyUnicode_IS_ASCII(self))
10267 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010268 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010269 PyUnicode_GET_LENGTH(self), maxcount
10270 );
10271 else
10272 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010273 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 PyUnicode_GET_LENGTH(self), maxcount
10275 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 case PyUnicode_2BYTE_KIND:
10277 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010278 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 PyUnicode_GET_LENGTH(self), maxcount
10280 );
10281 case PyUnicode_4BYTE_KIND:
10282 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010283 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 PyUnicode_GET_LENGTH(self), maxcount
10285 );
10286 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010287 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 }
10289
10290 if (PyUnicode_READY(substring) == -1)
10291 return NULL;
10292
10293 kind1 = PyUnicode_KIND(self);
10294 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 len1 = PyUnicode_GET_LENGTH(self);
10296 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010297 if (kind1 < kind2 || len1 < len2) {
10298 out = PyList_New(1);
10299 if (out == NULL)
10300 return NULL;
10301 Py_INCREF(self);
10302 PyList_SET_ITEM(out, 0, self);
10303 return out;
10304 }
10305 buf1 = PyUnicode_DATA(self);
10306 buf2 = PyUnicode_DATA(substring);
10307 if (kind2 != kind1) {
10308 buf2 = _PyUnicode_AsKind(substring, kind1);
10309 if (!buf2)
10310 return NULL;
10311 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010313 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010315 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10316 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010317 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010318 else
10319 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010320 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 break;
10322 case PyUnicode_2BYTE_KIND:
10323 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010324 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 break;
10326 case PyUnicode_4BYTE_KIND:
10327 out = ucs4lib_split(
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 default:
10331 out = NULL;
10332 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010333 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 PyMem_Free(buf2);
10335 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010336}
10337
Alexander Belopolsky40018472011-02-26 01:02:56 +000010338static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010339rsplit(PyObject *self,
10340 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010341 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010342{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010343 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 void *buf1, *buf2;
10345 Py_ssize_t len1, len2;
10346 PyObject* out;
10347
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010348 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010349 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 if (PyUnicode_READY(self) == -1)
10352 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010355 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010357 if (PyUnicode_IS_ASCII(self))
10358 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010359 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010360 PyUnicode_GET_LENGTH(self), maxcount
10361 );
10362 else
10363 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010364 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010365 PyUnicode_GET_LENGTH(self), maxcount
10366 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 case PyUnicode_2BYTE_KIND:
10368 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010369 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 PyUnicode_GET_LENGTH(self), maxcount
10371 );
10372 case PyUnicode_4BYTE_KIND:
10373 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010374 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 PyUnicode_GET_LENGTH(self), maxcount
10376 );
10377 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010378 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 }
10380
10381 if (PyUnicode_READY(substring) == -1)
10382 return NULL;
10383
10384 kind1 = PyUnicode_KIND(self);
10385 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 len1 = PyUnicode_GET_LENGTH(self);
10387 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010388 if (kind1 < kind2 || len1 < len2) {
10389 out = PyList_New(1);
10390 if (out == NULL)
10391 return NULL;
10392 Py_INCREF(self);
10393 PyList_SET_ITEM(out, 0, self);
10394 return out;
10395 }
10396 buf1 = PyUnicode_DATA(self);
10397 buf2 = PyUnicode_DATA(substring);
10398 if (kind2 != kind1) {
10399 buf2 = _PyUnicode_AsKind(substring, kind1);
10400 if (!buf2)
10401 return NULL;
10402 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010404 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10407 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010408 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010409 else
10410 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010411 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 break;
10413 case PyUnicode_2BYTE_KIND:
10414 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010415 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 break;
10417 case PyUnicode_4BYTE_KIND:
10418 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010419 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 break;
10421 default:
10422 out = NULL;
10423 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010424 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 PyMem_Free(buf2);
10426 return out;
10427}
10428
10429static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010430anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10431 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010433 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010435 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10436 return asciilib_find(buf1, len1, buf2, len2, offset);
10437 else
10438 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 case PyUnicode_2BYTE_KIND:
10440 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10441 case PyUnicode_4BYTE_KIND:
10442 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10443 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010444 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445}
10446
10447static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010448anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10449 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010451 switch (kind) {
10452 case PyUnicode_1BYTE_KIND:
10453 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10454 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10455 else
10456 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10457 case PyUnicode_2BYTE_KIND:
10458 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10459 case PyUnicode_4BYTE_KIND:
10460 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10461 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010462 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010463}
10464
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010465static void
10466replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10467 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10468{
10469 int kind = PyUnicode_KIND(u);
10470 void *data = PyUnicode_DATA(u);
10471 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10472 if (kind == PyUnicode_1BYTE_KIND) {
10473 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10474 (Py_UCS1 *)data + len,
10475 u1, u2, maxcount);
10476 }
10477 else if (kind == PyUnicode_2BYTE_KIND) {
10478 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10479 (Py_UCS2 *)data + len,
10480 u1, u2, maxcount);
10481 }
10482 else {
10483 assert(kind == PyUnicode_4BYTE_KIND);
10484 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10485 (Py_UCS4 *)data + len,
10486 u1, u2, maxcount);
10487 }
10488}
10489
Alexander Belopolsky40018472011-02-26 01:02:56 +000010490static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491replace(PyObject *self, PyObject *str1,
10492 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010493{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 PyObject *u;
10495 char *sbuf = PyUnicode_DATA(self);
10496 char *buf1 = PyUnicode_DATA(str1);
10497 char *buf2 = PyUnicode_DATA(str2);
10498 int srelease = 0, release1 = 0, release2 = 0;
10499 int skind = PyUnicode_KIND(self);
10500 int kind1 = PyUnicode_KIND(str1);
10501 int kind2 = PyUnicode_KIND(str2);
10502 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10503 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10504 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010505 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010506 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507
10508 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010509 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010511 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512
Victor Stinner59de0ee2011-10-07 10:01:28 +020010513 if (str1 == str2)
10514 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515
Victor Stinner49a0a212011-10-12 23:46:10 +020010516 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010517 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10518 if (maxchar < maxchar_str1)
10519 /* substring too wide to be present */
10520 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010521 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10522 /* Replacing str1 with str2 may cause a maxchar reduction in the
10523 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010524 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010525 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010527 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010528 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010530 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010532 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010533 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010534 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010535
Victor Stinner69ed0f42013-04-09 21:48:24 +020010536 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010537 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010538 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010539 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010540 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010542 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010544
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010545 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10546 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010547 }
10548 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 int rkind = skind;
10550 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010551 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 if (kind1 < rkind) {
10554 /* widen substring */
10555 buf1 = _PyUnicode_AsKind(str1, rkind);
10556 if (!buf1) goto error;
10557 release1 = 1;
10558 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010559 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010560 if (i < 0)
10561 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 if (rkind > kind2) {
10563 /* widen replacement */
10564 buf2 = _PyUnicode_AsKind(str2, rkind);
10565 if (!buf2) goto error;
10566 release2 = 1;
10567 }
10568 else if (rkind < kind2) {
10569 /* widen self and buf1 */
10570 rkind = kind2;
10571 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010572 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 sbuf = _PyUnicode_AsKind(self, rkind);
10574 if (!sbuf) goto error;
10575 srelease = 1;
10576 buf1 = _PyUnicode_AsKind(str1, rkind);
10577 if (!buf1) goto error;
10578 release1 = 1;
10579 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010580 u = PyUnicode_New(slen, maxchar);
10581 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010583 assert(PyUnicode_KIND(u) == rkind);
10584 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010585
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010587 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010588 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010590 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010592
10593 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010594 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010595 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010596 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010597 if (i == -1)
10598 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010599 memcpy(res + rkind * i,
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 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010603 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010605 }
10606 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010608 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 int rkind = skind;
10610 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010613 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 buf1 = _PyUnicode_AsKind(str1, rkind);
10615 if (!buf1) goto error;
10616 release1 = 1;
10617 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010618 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619 if (n == 0)
10620 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010622 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 buf2 = _PyUnicode_AsKind(str2, rkind);
10624 if (!buf2) goto error;
10625 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010628 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 rkind = kind2;
10630 sbuf = _PyUnicode_AsKind(self, rkind);
10631 if (!sbuf) goto error;
10632 srelease = 1;
10633 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010634 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 buf1 = _PyUnicode_AsKind(str1, rkind);
10636 if (!buf1) goto error;
10637 release1 = 1;
10638 }
10639 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10640 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010641 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 PyErr_SetString(PyExc_OverflowError,
10643 "replace string is too long");
10644 goto error;
10645 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010646 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010647 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010648 _Py_INCREF_UNICODE_EMPTY();
10649 if (!unicode_empty)
10650 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010651 u = unicode_empty;
10652 goto done;
10653 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010654 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 PyErr_SetString(PyExc_OverflowError,
10656 "replace string is too long");
10657 goto error;
10658 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010659 u = PyUnicode_New(new_size, maxchar);
10660 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010662 assert(PyUnicode_KIND(u) == rkind);
10663 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 ires = i = 0;
10665 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010666 while (n-- > 0) {
10667 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010668 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010669 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010670 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010671 if (j == -1)
10672 break;
10673 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010674 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010675 memcpy(res + rkind * ires,
10676 sbuf + rkind * i,
10677 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010679 }
10680 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010682 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010684 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010686 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010688 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010690 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010691 memcpy(res + rkind * ires,
10692 sbuf + rkind * i,
10693 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010694 }
10695 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010696 /* interleave */
10697 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010698 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010700 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010702 if (--n <= 0)
10703 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010704 memcpy(res + rkind * ires,
10705 sbuf + rkind * i,
10706 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 ires++;
10708 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010709 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010710 memcpy(res + rkind * ires,
10711 sbuf + rkind * i,
10712 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010713 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010714 }
10715
10716 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010717 unicode_adjust_maxchar(&u);
10718 if (u == NULL)
10719 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010721
10722 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 if (srelease)
10724 PyMem_FREE(sbuf);
10725 if (release1)
10726 PyMem_FREE(buf1);
10727 if (release2)
10728 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010729 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010731
Benjamin Peterson29060642009-01-31 22:14:21 +000010732 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010733 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010734 if (srelease)
10735 PyMem_FREE(sbuf);
10736 if (release1)
10737 PyMem_FREE(buf1);
10738 if (release2)
10739 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010740 return unicode_result_unchanged(self);
10741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 error:
10743 if (srelease && sbuf)
10744 PyMem_FREE(sbuf);
10745 if (release1 && buf1)
10746 PyMem_FREE(buf1);
10747 if (release2 && buf2)
10748 PyMem_FREE(buf2);
10749 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750}
10751
10752/* --- Unicode Object Methods --------------------------------------------- */
10753
INADA Naoki3ae20562017-01-16 20:41:20 +090010754/*[clinic input]
10755str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756
INADA Naoki3ae20562017-01-16 20:41:20 +090010757Return a version of the string where each word is titlecased.
10758
10759More specifically, words start with uppercased characters and all remaining
10760cased characters have lower case.
10761[clinic start generated code]*/
10762
10763static PyObject *
10764unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010765/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010767 if (PyUnicode_READY(self) == -1)
10768 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010769 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770}
10771
INADA Naoki3ae20562017-01-16 20:41:20 +090010772/*[clinic input]
10773str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774
INADA Naoki3ae20562017-01-16 20:41:20 +090010775Return a capitalized version of the string.
10776
10777More specifically, make the first character have upper case and the rest lower
10778case.
10779[clinic start generated code]*/
10780
10781static PyObject *
10782unicode_capitalize_impl(PyObject *self)
10783/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010785 if (PyUnicode_READY(self) == -1)
10786 return NULL;
10787 if (PyUnicode_GET_LENGTH(self) == 0)
10788 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010789 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010790}
10791
INADA Naoki3ae20562017-01-16 20:41:20 +090010792/*[clinic input]
10793str.casefold as unicode_casefold
10794
10795Return a version of the string suitable for caseless comparisons.
10796[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010797
10798static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010799unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010800/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010801{
10802 if (PyUnicode_READY(self) == -1)
10803 return NULL;
10804 if (PyUnicode_IS_ASCII(self))
10805 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010806 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010807}
10808
10809
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010810/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010811
10812static int
10813convert_uc(PyObject *obj, void *addr)
10814{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010816
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010817 if (!PyUnicode_Check(obj)) {
10818 PyErr_Format(PyExc_TypeError,
10819 "The fill character must be a unicode character, "
10820 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010821 return 0;
10822 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010823 if (PyUnicode_READY(obj) < 0)
10824 return 0;
10825 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010826 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010827 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010828 return 0;
10829 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010830 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010831 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010832}
10833
INADA Naoki3ae20562017-01-16 20:41:20 +090010834/*[clinic input]
10835str.center as unicode_center
10836
10837 width: Py_ssize_t
10838 fillchar: Py_UCS4 = ' '
10839 /
10840
10841Return a centered string of length width.
10842
10843Padding is done using the specified fill character (default is a space).
10844[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845
10846static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010847unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10848/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010850 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851
Benjamin Petersonbac79492012-01-14 13:34:47 -050010852 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853 return NULL;
10854
Victor Stinnerc4b49542011-12-11 22:44:26 +010010855 if (PyUnicode_GET_LENGTH(self) >= width)
10856 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010857
Victor Stinnerc4b49542011-12-11 22:44:26 +010010858 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010859 left = marg / 2 + (marg & width & 1);
10860
Victor Stinner9310abb2011-10-05 00:59:23 +020010861 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010862}
10863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010864/* This function assumes that str1 and str2 are readied by the caller. */
10865
Marc-André Lemburge5034372000-08-08 08:04:29 +000010866static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010867unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010868{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010869#define COMPARE(TYPE1, TYPE2) \
10870 do { \
10871 TYPE1* p1 = (TYPE1 *)data1; \
10872 TYPE2* p2 = (TYPE2 *)data2; \
10873 TYPE1* end = p1 + len; \
10874 Py_UCS4 c1, c2; \
10875 for (; p1 != end; p1++, p2++) { \
10876 c1 = *p1; \
10877 c2 = *p2; \
10878 if (c1 != c2) \
10879 return (c1 < c2) ? -1 : 1; \
10880 } \
10881 } \
10882 while (0)
10883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010884 int kind1, kind2;
10885 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010886 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010888 kind1 = PyUnicode_KIND(str1);
10889 kind2 = PyUnicode_KIND(str2);
10890 data1 = PyUnicode_DATA(str1);
10891 data2 = PyUnicode_DATA(str2);
10892 len1 = PyUnicode_GET_LENGTH(str1);
10893 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010894 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010895
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010896 switch(kind1) {
10897 case PyUnicode_1BYTE_KIND:
10898 {
10899 switch(kind2) {
10900 case PyUnicode_1BYTE_KIND:
10901 {
10902 int cmp = memcmp(data1, data2, len);
10903 /* normalize result of memcmp() into the range [-1; 1] */
10904 if (cmp < 0)
10905 return -1;
10906 if (cmp > 0)
10907 return 1;
10908 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010909 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010910 case PyUnicode_2BYTE_KIND:
10911 COMPARE(Py_UCS1, Py_UCS2);
10912 break;
10913 case PyUnicode_4BYTE_KIND:
10914 COMPARE(Py_UCS1, Py_UCS4);
10915 break;
10916 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010917 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010918 }
10919 break;
10920 }
10921 case PyUnicode_2BYTE_KIND:
10922 {
10923 switch(kind2) {
10924 case PyUnicode_1BYTE_KIND:
10925 COMPARE(Py_UCS2, Py_UCS1);
10926 break;
10927 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010928 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010929 COMPARE(Py_UCS2, Py_UCS2);
10930 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010931 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010932 case PyUnicode_4BYTE_KIND:
10933 COMPARE(Py_UCS2, Py_UCS4);
10934 break;
10935 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010936 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010937 }
10938 break;
10939 }
10940 case PyUnicode_4BYTE_KIND:
10941 {
10942 switch(kind2) {
10943 case PyUnicode_1BYTE_KIND:
10944 COMPARE(Py_UCS4, Py_UCS1);
10945 break;
10946 case PyUnicode_2BYTE_KIND:
10947 COMPARE(Py_UCS4, Py_UCS2);
10948 break;
10949 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010950 {
10951#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10952 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10953 /* normalize result of wmemcmp() into the range [-1; 1] */
10954 if (cmp < 0)
10955 return -1;
10956 if (cmp > 0)
10957 return 1;
10958#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010959 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010960#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010961 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010962 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010963 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010964 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010965 }
10966 break;
10967 }
10968 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010969 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010970 }
10971
Victor Stinner770e19e2012-10-04 22:59:45 +020010972 if (len1 == len2)
10973 return 0;
10974 if (len1 < len2)
10975 return -1;
10976 else
10977 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010978
10979#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010980}
10981
Benjamin Peterson621b4302016-09-09 13:54:34 -070010982static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010983unicode_compare_eq(PyObject *str1, PyObject *str2)
10984{
10985 int kind;
10986 void *data1, *data2;
10987 Py_ssize_t len;
10988 int cmp;
10989
Victor Stinnere5567ad2012-10-23 02:48:49 +020010990 len = PyUnicode_GET_LENGTH(str1);
10991 if (PyUnicode_GET_LENGTH(str2) != len)
10992 return 0;
10993 kind = PyUnicode_KIND(str1);
10994 if (PyUnicode_KIND(str2) != kind)
10995 return 0;
10996 data1 = PyUnicode_DATA(str1);
10997 data2 = PyUnicode_DATA(str2);
10998
10999 cmp = memcmp(data1, data2, len * kind);
11000 return (cmp == 0);
11001}
11002
11003
Alexander Belopolsky40018472011-02-26 01:02:56 +000011004int
11005PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11008 if (PyUnicode_READY(left) == -1 ||
11009 PyUnicode_READY(right) == -1)
11010 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011011
11012 /* a string is equal to itself */
11013 if (left == right)
11014 return 0;
11015
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011016 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011017 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011018 PyErr_Format(PyExc_TypeError,
11019 "Can't compare %.100s and %.100s",
11020 left->ob_type->tp_name,
11021 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022 return -1;
11023}
11024
Martin v. Löwis5b222132007-06-10 09:51:05 +000011025int
11026PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11027{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011028 Py_ssize_t i;
11029 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011030 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011031 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011032
Victor Stinner910337b2011-10-03 03:20:16 +020011033 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011034 if (!PyUnicode_IS_READY(uni)) {
11035 const wchar_t *ws = _PyUnicode_WSTR(uni);
11036 /* Compare Unicode string and source character set string */
11037 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11038 if (chr != ustr[i])
11039 return (chr < ustr[i]) ? -1 : 1;
11040 }
11041 /* This check keeps Python strings that end in '\0' from comparing equal
11042 to C strings identical up to that point. */
11043 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11044 return 1; /* uni is longer */
11045 if (ustr[i])
11046 return -1; /* str is longer */
11047 return 0;
11048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011049 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011050 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011051 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011052 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011053 size_t len, len2 = strlen(str);
11054 int cmp;
11055
11056 len = Py_MIN(len1, len2);
11057 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011058 if (cmp != 0) {
11059 if (cmp < 0)
11060 return -1;
11061 else
11062 return 1;
11063 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011064 if (len1 > len2)
11065 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011066 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011067 return -1; /* str is longer */
11068 return 0;
11069 }
11070 else {
11071 void *data = PyUnicode_DATA(uni);
11072 /* Compare Unicode string and source character set string */
11073 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011074 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011075 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11076 /* This check keeps Python strings that end in '\0' from comparing equal
11077 to C strings identical up to that point. */
11078 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11079 return 1; /* uni is longer */
11080 if (str[i])
11081 return -1; /* str is longer */
11082 return 0;
11083 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011084}
11085
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011086static int
11087non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11088{
11089 size_t i, len;
11090 const wchar_t *p;
11091 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11092 if (strlen(str) != len)
11093 return 0;
11094 p = _PyUnicode_WSTR(unicode);
11095 assert(p);
11096 for (i = 0; i < len; i++) {
11097 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011098 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011099 return 0;
11100 }
11101 return 1;
11102}
11103
11104int
11105_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11106{
11107 size_t len;
11108 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011109 assert(str);
11110#ifndef NDEBUG
11111 for (const char *p = str; *p; p++) {
11112 assert((unsigned char)*p < 128);
11113 }
11114#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011115 if (PyUnicode_READY(unicode) == -1) {
11116 /* Memory error or bad data */
11117 PyErr_Clear();
11118 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11119 }
11120 if (!PyUnicode_IS_ASCII(unicode))
11121 return 0;
11122 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11123 return strlen(str) == len &&
11124 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11125}
11126
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011127int
11128_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11129{
11130 PyObject *right_uni;
11131 Py_hash_t hash;
11132
11133 assert(_PyUnicode_CHECK(left));
11134 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011135#ifndef NDEBUG
11136 for (const char *p = right->string; *p; p++) {
11137 assert((unsigned char)*p < 128);
11138 }
11139#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011140
11141 if (PyUnicode_READY(left) == -1) {
11142 /* memory error or bad data */
11143 PyErr_Clear();
11144 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11145 }
11146
11147 if (!PyUnicode_IS_ASCII(left))
11148 return 0;
11149
11150 right_uni = _PyUnicode_FromId(right); /* borrowed */
11151 if (right_uni == NULL) {
11152 /* memory error or bad data */
11153 PyErr_Clear();
11154 return _PyUnicode_EqualToASCIIString(left, right->string);
11155 }
11156
11157 if (left == right_uni)
11158 return 1;
11159
11160 if (PyUnicode_CHECK_INTERNED(left))
11161 return 0;
11162
11163 assert(_PyUnicode_HASH(right_uni) != 1);
11164 hash = _PyUnicode_HASH(left);
11165 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11166 return 0;
11167
11168 return unicode_compare_eq(left, right_uni);
11169}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011170
Alexander Belopolsky40018472011-02-26 01:02:56 +000011171PyObject *
11172PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011173{
11174 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011175
Victor Stinnere5567ad2012-10-23 02:48:49 +020011176 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11177 Py_RETURN_NOTIMPLEMENTED;
11178
11179 if (PyUnicode_READY(left) == -1 ||
11180 PyUnicode_READY(right) == -1)
11181 return NULL;
11182
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011183 if (left == right) {
11184 switch (op) {
11185 case Py_EQ:
11186 case Py_LE:
11187 case Py_GE:
11188 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011189 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011190 case Py_NE:
11191 case Py_LT:
11192 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011193 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011194 default:
11195 PyErr_BadArgument();
11196 return NULL;
11197 }
11198 }
11199 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011200 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011201 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011202 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011203 }
11204 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011205 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011206 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011207 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011208}
11209
Alexander Belopolsky40018472011-02-26 01:02:56 +000011210int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011211_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11212{
11213 return unicode_eq(aa, bb);
11214}
11215
11216int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011217PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011218{
Victor Stinner77282cb2013-04-14 19:22:47 +020011219 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 void *buf1, *buf2;
11221 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011222 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011223
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011224 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011225 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011226 "'in <string>' requires string as left operand, not %.100s",
11227 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011228 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011229 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011230 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011231 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011232 if (ensure_unicode(str) < 0)
11233 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011236 kind2 = PyUnicode_KIND(substr);
11237 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011238 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011240 len2 = PyUnicode_GET_LENGTH(substr);
11241 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011242 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011243 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011244 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011245 if (len2 == 1) {
11246 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11247 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011248 return result;
11249 }
11250 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011251 buf2 = _PyUnicode_AsKind(substr, kind1);
11252 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011253 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255
Victor Stinner77282cb2013-04-14 19:22:47 +020011256 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011257 case PyUnicode_1BYTE_KIND:
11258 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11259 break;
11260 case PyUnicode_2BYTE_KIND:
11261 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11262 break;
11263 case PyUnicode_4BYTE_KIND:
11264 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11265 break;
11266 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011267 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011269
Victor Stinner77282cb2013-04-14 19:22:47 +020011270 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 PyMem_Free(buf2);
11272
Guido van Rossum403d68b2000-03-13 15:55:09 +000011273 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011274}
11275
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276/* Concat to string or Unicode object giving a new Unicode object. */
11277
Alexander Belopolsky40018472011-02-26 01:02:56 +000011278PyObject *
11279PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011281 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011282 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011283 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011285 if (ensure_unicode(left) < 0)
11286 return NULL;
11287
11288 if (!PyUnicode_Check(right)) {
11289 PyErr_Format(PyExc_TypeError,
11290 "can only concatenate str (not \"%.200s\") to str",
11291 right->ob_type->tp_name);
11292 return NULL;
11293 }
11294 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011295 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296
11297 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011298 if (left == unicode_empty)
11299 return PyUnicode_FromObject(right);
11300 if (right == unicode_empty)
11301 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011303 left_len = PyUnicode_GET_LENGTH(left);
11304 right_len = PyUnicode_GET_LENGTH(right);
11305 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011306 PyErr_SetString(PyExc_OverflowError,
11307 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011308 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011309 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011310 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011311
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011312 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11313 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011314 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011317 result = PyUnicode_New(new_len, maxchar);
11318 if (result == NULL)
11319 return NULL;
11320 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11321 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11322 assert(_PyUnicode_CheckConsistency(result, 1));
11323 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324}
11325
Walter Dörwald1ab83302007-05-18 17:15:44 +000011326void
Victor Stinner23e56682011-10-03 03:54:37 +020011327PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011328{
Victor Stinner23e56682011-10-03 03:54:37 +020011329 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011330 Py_UCS4 maxchar, maxchar2;
11331 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011332
11333 if (p_left == NULL) {
11334 if (!PyErr_Occurred())
11335 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011336 return;
11337 }
Victor Stinner23e56682011-10-03 03:54:37 +020011338 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011339 if (right == NULL || left == NULL
11340 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011341 if (!PyErr_Occurred())
11342 PyErr_BadInternalCall();
11343 goto error;
11344 }
11345
Benjamin Petersonbac79492012-01-14 13:34:47 -050011346 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011347 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011348 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011349 goto error;
11350
Victor Stinner488fa492011-12-12 00:01:39 +010011351 /* Shortcuts */
11352 if (left == unicode_empty) {
11353 Py_DECREF(left);
11354 Py_INCREF(right);
11355 *p_left = right;
11356 return;
11357 }
11358 if (right == unicode_empty)
11359 return;
11360
11361 left_len = PyUnicode_GET_LENGTH(left);
11362 right_len = PyUnicode_GET_LENGTH(right);
11363 if (left_len > PY_SSIZE_T_MAX - right_len) {
11364 PyErr_SetString(PyExc_OverflowError,
11365 "strings are too large to concat");
11366 goto error;
11367 }
11368 new_len = left_len + right_len;
11369
11370 if (unicode_modifiable(left)
11371 && PyUnicode_CheckExact(right)
11372 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011373 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11374 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011375 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011376 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011377 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11378 {
11379 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011380 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011381 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011382
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011383 /* copy 'right' into the newly allocated area of 'left' */
11384 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011385 }
Victor Stinner488fa492011-12-12 00:01:39 +010011386 else {
11387 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11388 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011389 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011390
Victor Stinner488fa492011-12-12 00:01:39 +010011391 /* Concat the two Unicode strings */
11392 res = PyUnicode_New(new_len, maxchar);
11393 if (res == NULL)
11394 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011395 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11396 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011397 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011398 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011399 }
11400 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011401 return;
11402
11403error:
Victor Stinner488fa492011-12-12 00:01:39 +010011404 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011405}
11406
11407void
11408PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11409{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011410 PyUnicode_Append(pleft, right);
11411 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011412}
11413
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011414/*
11415Wraps stringlib_parse_args_finds() and additionally ensures that the
11416first argument is a unicode object.
11417*/
11418
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011419static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011420parse_args_finds_unicode(const char * function_name, PyObject *args,
11421 PyObject **substring,
11422 Py_ssize_t *start, Py_ssize_t *end)
11423{
11424 if(stringlib_parse_args_finds(function_name, args, substring,
11425 start, end)) {
11426 if (ensure_unicode(*substring) < 0)
11427 return 0;
11428 return 1;
11429 }
11430 return 0;
11431}
11432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011433PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011436Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011437string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011438interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
11440static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011441unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011443 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011444 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011445 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011447 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 void *buf1, *buf2;
11449 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011451 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 kind1 = PyUnicode_KIND(self);
11455 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011456 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011457 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 len1 = PyUnicode_GET_LENGTH(self);
11460 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011462 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011463 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011464
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011465 buf1 = PyUnicode_DATA(self);
11466 buf2 = PyUnicode_DATA(substring);
11467 if (kind2 != kind1) {
11468 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011469 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011470 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011471 }
11472 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 case PyUnicode_1BYTE_KIND:
11474 iresult = ucs1lib_count(
11475 ((Py_UCS1*)buf1) + start, end - start,
11476 buf2, len2, PY_SSIZE_T_MAX
11477 );
11478 break;
11479 case PyUnicode_2BYTE_KIND:
11480 iresult = ucs2lib_count(
11481 ((Py_UCS2*)buf1) + start, end - start,
11482 buf2, len2, PY_SSIZE_T_MAX
11483 );
11484 break;
11485 case PyUnicode_4BYTE_KIND:
11486 iresult = ucs4lib_count(
11487 ((Py_UCS4*)buf1) + start, end - start,
11488 buf2, len2, PY_SSIZE_T_MAX
11489 );
11490 break;
11491 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011492 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 }
11494
11495 result = PyLong_FromSsize_t(iresult);
11496
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011497 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500 return result;
11501}
11502
INADA Naoki3ae20562017-01-16 20:41:20 +090011503/*[clinic input]
11504str.encode as unicode_encode
11505
11506 encoding: str(c_default="NULL") = 'utf-8'
11507 The encoding in which to encode the string.
11508 errors: str(c_default="NULL") = 'strict'
11509 The error handling scheme to use for encoding errors.
11510 The default is 'strict' meaning that encoding errors raise a
11511 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11512 'xmlcharrefreplace' as well as any other name registered with
11513 codecs.register_error that can handle UnicodeEncodeErrors.
11514
11515Encode the string using the codec registered for encoding.
11516[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517
11518static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011519unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011520/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011522 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011523}
11524
INADA Naoki3ae20562017-01-16 20:41:20 +090011525/*[clinic input]
11526str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527
INADA Naoki3ae20562017-01-16 20:41:20 +090011528 tabsize: int = 8
11529
11530Return a copy where all tab characters are expanded using spaces.
11531
11532If tabsize is not given, a tab size of 8 characters is assumed.
11533[clinic start generated code]*/
11534
11535static PyObject *
11536unicode_expandtabs_impl(PyObject *self, int tabsize)
11537/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011539 Py_ssize_t i, j, line_pos, src_len, incr;
11540 Py_UCS4 ch;
11541 PyObject *u;
11542 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011543 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011544 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545
Antoine Pitrou22425222011-10-04 19:10:51 +020011546 if (PyUnicode_READY(self) == -1)
11547 return NULL;
11548
Thomas Wouters7e474022000-07-16 12:04:32 +000011549 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011550 src_len = PyUnicode_GET_LENGTH(self);
11551 i = j = line_pos = 0;
11552 kind = PyUnicode_KIND(self);
11553 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011554 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011555 for (; i < src_len; i++) {
11556 ch = PyUnicode_READ(kind, src_data, i);
11557 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011558 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011559 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011560 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011561 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011562 goto overflow;
11563 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011565 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011568 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011569 goto overflow;
11570 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011572 if (ch == '\n' || ch == '\r')
11573 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011575 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011576 if (!found)
11577 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011578
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011580 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581 if (!u)
11582 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011583 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584
Antoine Pitroue71d5742011-10-04 15:55:09 +020011585 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586
Antoine Pitroue71d5742011-10-04 15:55:09 +020011587 for (; i < src_len; i++) {
11588 ch = PyUnicode_READ(kind, src_data, i);
11589 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011591 incr = tabsize - (line_pos % tabsize);
11592 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011593 FILL(kind, dest_data, ' ', j, incr);
11594 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011596 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011597 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011598 line_pos++;
11599 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011600 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011601 if (ch == '\n' || ch == '\r')
11602 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011604 }
11605 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011606 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011607
Antoine Pitroue71d5742011-10-04 15:55:09 +020011608 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011609 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11610 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611}
11612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011613PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615\n\
11616Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011617such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618arguments start and end are interpreted as in slice notation.\n\
11619\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011620Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621
11622static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011625 /* initialize variables to prevent gcc warning */
11626 PyObject *substring = NULL;
11627 Py_ssize_t start = 0;
11628 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011629 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011631 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011634 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011635 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011637 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 if (result == -2)
11640 return NULL;
11641
Christian Heimes217cfd12007-12-02 14:31:20 +000011642 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643}
11644
11645static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011646unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011648 void *data;
11649 enum PyUnicode_Kind kind;
11650 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011651
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011652 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011653 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011655 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011656 if (PyUnicode_READY(self) == -1) {
11657 return NULL;
11658 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011659 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11660 PyErr_SetString(PyExc_IndexError, "string index out of range");
11661 return NULL;
11662 }
11663 kind = PyUnicode_KIND(self);
11664 data = PyUnicode_DATA(self);
11665 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011666 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667}
11668
Guido van Rossumc2504932007-09-18 19:42:40 +000011669/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011670 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011671static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011672unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673{
Guido van Rossumc2504932007-09-18 19:42:40 +000011674 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011675 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011676
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011677#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011678 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011679#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (_PyUnicode_HASH(self) != -1)
11681 return _PyUnicode_HASH(self);
11682 if (PyUnicode_READY(self) == -1)
11683 return -1;
11684 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011685 /*
11686 We make the hash of the empty string be 0, rather than using
11687 (prefix ^ suffix), since this slightly obfuscates the hash secret
11688 */
11689 if (len == 0) {
11690 _PyUnicode_HASH(self) = 0;
11691 return 0;
11692 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011693 x = _Py_HashBytes(PyUnicode_DATA(self),
11694 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011696 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697}
11698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011699PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011702Return the lowest index in S where substring sub is found, \n\
11703such that sub is contained within S[start:end]. Optional\n\
11704arguments start and end are interpreted as in slice notation.\n\
11705\n\
11706Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
11708static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011711 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011712 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011713 PyObject *substring = NULL;
11714 Py_ssize_t start = 0;
11715 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011717 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011720 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011723 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 if (result == -2)
11726 return NULL;
11727
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 if (result < 0) {
11729 PyErr_SetString(PyExc_ValueError, "substring not found");
11730 return NULL;
11731 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011732
Christian Heimes217cfd12007-12-02 14:31:20 +000011733 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734}
11735
INADA Naoki3ae20562017-01-16 20:41:20 +090011736/*[clinic input]
11737str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
INADA Naoki3ae20562017-01-16 20:41:20 +090011739Return True if the string is a lowercase string, False otherwise.
11740
11741A string is lowercase if all cased characters in the string are lowercase and
11742there is at least one cased character in the string.
11743[clinic start generated code]*/
11744
11745static PyObject *
11746unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011747/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011749 Py_ssize_t i, length;
11750 int kind;
11751 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752 int cased;
11753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 if (PyUnicode_READY(self) == -1)
11755 return NULL;
11756 length = PyUnicode_GET_LENGTH(self);
11757 kind = PyUnicode_KIND(self);
11758 data = PyUnicode_DATA(self);
11759
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761 if (length == 1)
11762 return PyBool_FromLong(
11763 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011765 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011767 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011768
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 for (i = 0; i < length; i++) {
11771 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011772
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011774 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011775 else if (!cased && Py_UNICODE_ISLOWER(ch))
11776 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011778 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779}
11780
INADA Naoki3ae20562017-01-16 20:41:20 +090011781/*[clinic input]
11782str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
INADA Naoki3ae20562017-01-16 20:41:20 +090011784Return True if the string is an uppercase string, False otherwise.
11785
11786A string is uppercase if all cased characters in the string are uppercase and
11787there is at least one cased character in the string.
11788[clinic start generated code]*/
11789
11790static PyObject *
11791unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011792/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 Py_ssize_t i, length;
11795 int kind;
11796 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797 int cased;
11798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 if (PyUnicode_READY(self) == -1)
11800 return NULL;
11801 length = PyUnicode_GET_LENGTH(self);
11802 kind = PyUnicode_KIND(self);
11803 data = PyUnicode_DATA(self);
11804
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (length == 1)
11807 return PyBool_FromLong(
11808 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011810 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011812 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011813
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 for (i = 0; i < length; i++) {
11816 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011817
Benjamin Peterson29060642009-01-31 22:14:21 +000011818 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011819 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011820 else if (!cased && Py_UNICODE_ISUPPER(ch))
11821 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011823 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824}
11825
INADA Naoki3ae20562017-01-16 20:41:20 +090011826/*[clinic input]
11827str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828
INADA Naoki3ae20562017-01-16 20:41:20 +090011829Return True if the string is a title-cased string, False otherwise.
11830
11831In a title-cased string, upper- and title-case characters may only
11832follow uncased characters and lowercase characters only cased ones.
11833[clinic start generated code]*/
11834
11835static PyObject *
11836unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011837/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 Py_ssize_t i, length;
11840 int kind;
11841 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842 int cased, previous_is_cased;
11843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011844 if (PyUnicode_READY(self) == -1)
11845 return NULL;
11846 length = PyUnicode_GET_LENGTH(self);
11847 kind = PyUnicode_KIND(self);
11848 data = PyUnicode_DATA(self);
11849
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 if (length == 1) {
11852 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11853 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11854 (Py_UNICODE_ISUPPER(ch) != 0));
11855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011857 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011859 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011860
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861 cased = 0;
11862 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 for (i = 0; i < length; i++) {
11864 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011865
Benjamin Peterson29060642009-01-31 22:14:21 +000011866 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11867 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011868 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011869 previous_is_cased = 1;
11870 cased = 1;
11871 }
11872 else if (Py_UNICODE_ISLOWER(ch)) {
11873 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011874 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011875 previous_is_cased = 1;
11876 cased = 1;
11877 }
11878 else
11879 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011881 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882}
11883
INADA Naoki3ae20562017-01-16 20:41:20 +090011884/*[clinic input]
11885str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886
INADA Naoki3ae20562017-01-16 20:41:20 +090011887Return True if the string is a whitespace string, False otherwise.
11888
11889A string is whitespace if all characters in the string are whitespace and there
11890is at least one character in the string.
11891[clinic start generated code]*/
11892
11893static PyObject *
11894unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011895/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 Py_ssize_t i, length;
11898 int kind;
11899 void *data;
11900
11901 if (PyUnicode_READY(self) == -1)
11902 return NULL;
11903 length = PyUnicode_GET_LENGTH(self);
11904 kind = PyUnicode_KIND(self);
11905 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 if (length == 1)
11909 return PyBool_FromLong(
11910 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011912 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011914 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 for (i = 0; i < length; i++) {
11917 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011918 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011919 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011921 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922}
11923
INADA Naoki3ae20562017-01-16 20:41:20 +090011924/*[clinic input]
11925str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011926
INADA Naoki3ae20562017-01-16 20:41:20 +090011927Return True if the string is an alphabetic string, False otherwise.
11928
11929A string is alphabetic if all characters in the string are alphabetic and there
11930is at least one character in the string.
11931[clinic start generated code]*/
11932
11933static PyObject *
11934unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011935/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011936{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 Py_ssize_t i, length;
11938 int kind;
11939 void *data;
11940
11941 if (PyUnicode_READY(self) == -1)
11942 return NULL;
11943 length = PyUnicode_GET_LENGTH(self);
11944 kind = PyUnicode_KIND(self);
11945 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011946
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011947 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 if (length == 1)
11949 return PyBool_FromLong(
11950 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011951
11952 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011954 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 for (i = 0; i < length; i++) {
11957 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011958 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011959 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011960 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011961}
11962
INADA Naoki3ae20562017-01-16 20:41:20 +090011963/*[clinic input]
11964str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011965
INADA Naoki3ae20562017-01-16 20:41:20 +090011966Return True if the string is an alpha-numeric string, False otherwise.
11967
11968A string is alpha-numeric if all characters in the string are alpha-numeric and
11969there is at least one character in the string.
11970[clinic start generated code]*/
11971
11972static PyObject *
11973unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011974/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011975{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 int kind;
11977 void *data;
11978 Py_ssize_t len, i;
11979
11980 if (PyUnicode_READY(self) == -1)
11981 return NULL;
11982
11983 kind = PyUnicode_KIND(self);
11984 data = PyUnicode_DATA(self);
11985 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011986
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011987 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 if (len == 1) {
11989 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11990 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11991 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011992
11993 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011995 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 for (i = 0; i < len; i++) {
11998 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011999 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012000 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012001 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012002 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012003}
12004
INADA Naoki3ae20562017-01-16 20:41:20 +090012005/*[clinic input]
12006str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007
INADA Naoki3ae20562017-01-16 20:41:20 +090012008Return True if the string is a decimal string, False otherwise.
12009
12010A string is a decimal string if all characters in the string are decimal and
12011there is at least one character in the string.
12012[clinic start generated code]*/
12013
12014static PyObject *
12015unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012016/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012017{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 Py_ssize_t i, length;
12019 int kind;
12020 void *data;
12021
12022 if (PyUnicode_READY(self) == -1)
12023 return NULL;
12024 length = PyUnicode_GET_LENGTH(self);
12025 kind = PyUnicode_KIND(self);
12026 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027
Guido van Rossumd57fd912000-03-10 22:53:23 +000012028 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 if (length == 1)
12030 return PyBool_FromLong(
12031 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012033 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012035 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 for (i = 0; i < length; i++) {
12038 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012039 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012041 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042}
12043
INADA Naoki3ae20562017-01-16 20:41:20 +090012044/*[clinic input]
12045str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046
INADA Naoki3ae20562017-01-16 20:41:20 +090012047Return True if the string is a digit string, False otherwise.
12048
12049A string is a digit string if all characters in the string are digits and there
12050is at least one character in the string.
12051[clinic start generated code]*/
12052
12053static PyObject *
12054unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012055/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 Py_ssize_t i, length;
12058 int kind;
12059 void *data;
12060
12061 if (PyUnicode_READY(self) == -1)
12062 return NULL;
12063 length = PyUnicode_GET_LENGTH(self);
12064 kind = PyUnicode_KIND(self);
12065 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (length == 1) {
12069 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12070 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12071 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012073 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012075 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 for (i = 0; i < length; i++) {
12078 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012079 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012081 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012082}
12083
INADA Naoki3ae20562017-01-16 20:41:20 +090012084/*[clinic input]
12085str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086
INADA Naoki3ae20562017-01-16 20:41:20 +090012087Return True if the string is a numeric string, False otherwise.
12088
12089A string is numeric if all characters in the string are numeric and there is at
12090least one character in the string.
12091[clinic start generated code]*/
12092
12093static PyObject *
12094unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012095/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 Py_ssize_t i, length;
12098 int kind;
12099 void *data;
12100
12101 if (PyUnicode_READY(self) == -1)
12102 return NULL;
12103 length = PyUnicode_GET_LENGTH(self);
12104 kind = PyUnicode_KIND(self);
12105 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 if (length == 1)
12109 return PyBool_FromLong(
12110 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012112 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012113 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012114 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012115
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 for (i = 0; i < length; i++) {
12117 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012118 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012120 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121}
12122
Martin v. Löwis47383402007-08-15 07:32:56 +000012123int
12124PyUnicode_IsIdentifier(PyObject *self)
12125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012126 int kind;
12127 void *data;
12128 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012129 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 if (PyUnicode_READY(self) == -1) {
12132 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012133 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 }
12135
12136 /* Special case for empty strings */
12137 if (PyUnicode_GET_LENGTH(self) == 0)
12138 return 0;
12139 kind = PyUnicode_KIND(self);
12140 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012141
12142 /* PEP 3131 says that the first character must be in
12143 XID_Start and subsequent characters in XID_Continue,
12144 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012145 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012146 letters, digits, underscore). However, given the current
12147 definition of XID_Start and XID_Continue, it is sufficient
12148 to check just for these, except that _ must be allowed
12149 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012151 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012152 return 0;
12153
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012154 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012156 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012157 return 1;
12158}
12159
INADA Naoki3ae20562017-01-16 20:41:20 +090012160/*[clinic input]
12161str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012162
INADA Naoki3ae20562017-01-16 20:41:20 +090012163Return True if the string is a valid Python identifier, False otherwise.
12164
12165Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12166"class".
12167[clinic start generated code]*/
12168
12169static PyObject *
12170unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012171/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012172{
12173 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12174}
12175
INADA Naoki3ae20562017-01-16 20:41:20 +090012176/*[clinic input]
12177str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012178
INADA Naoki3ae20562017-01-16 20:41:20 +090012179Return True if the string is printable, False otherwise.
12180
12181A string is printable if all of its characters are considered printable in
12182repr() or if it is empty.
12183[clinic start generated code]*/
12184
12185static PyObject *
12186unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012187/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012188{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 Py_ssize_t i, length;
12190 int kind;
12191 void *data;
12192
12193 if (PyUnicode_READY(self) == -1)
12194 return NULL;
12195 length = PyUnicode_GET_LENGTH(self);
12196 kind = PyUnicode_KIND(self);
12197 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012198
12199 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 if (length == 1)
12201 return PyBool_FromLong(
12202 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 for (i = 0; i < length; i++) {
12205 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012206 Py_RETURN_FALSE;
12207 }
12208 }
12209 Py_RETURN_TRUE;
12210}
12211
INADA Naoki3ae20562017-01-16 20:41:20 +090012212/*[clinic input]
12213str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214
INADA Naoki3ae20562017-01-16 20:41:20 +090012215 iterable: object
12216 /
12217
12218Concatenate any number of strings.
12219
Martin Panter91a88662017-01-24 00:30:06 +000012220The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012221The result is returned as a new string.
12222
12223Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12224[clinic start generated code]*/
12225
12226static PyObject *
12227unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012228/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229{
INADA Naoki3ae20562017-01-16 20:41:20 +090012230 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231}
12232
Martin v. Löwis18e16552006-02-15 17:27:45 +000012233static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012234unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 if (PyUnicode_READY(self) == -1)
12237 return -1;
12238 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239}
12240
INADA Naoki3ae20562017-01-16 20:41:20 +090012241/*[clinic input]
12242str.ljust as unicode_ljust
12243
12244 width: Py_ssize_t
12245 fillchar: Py_UCS4 = ' '
12246 /
12247
12248Return a left-justified string of length width.
12249
12250Padding is done using the specified fill character (default is a space).
12251[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252
12253static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012254unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12255/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012257 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012258 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
Victor Stinnerc4b49542011-12-11 22:44:26 +010012260 if (PyUnicode_GET_LENGTH(self) >= width)
12261 return unicode_result_unchanged(self);
12262
12263 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264}
12265
INADA Naoki3ae20562017-01-16 20:41:20 +090012266/*[clinic input]
12267str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268
INADA Naoki3ae20562017-01-16 20:41:20 +090012269Return a copy of the string converted to lowercase.
12270[clinic start generated code]*/
12271
12272static PyObject *
12273unicode_lower_impl(PyObject *self)
12274/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012276 if (PyUnicode_READY(self) == -1)
12277 return NULL;
12278 if (PyUnicode_IS_ASCII(self))
12279 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012280 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281}
12282
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012283#define LEFTSTRIP 0
12284#define RIGHTSTRIP 1
12285#define BOTHSTRIP 2
12286
12287/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012288static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012289
INADA Naoki3ae20562017-01-16 20:41:20 +090012290#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012291
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012292/* externally visible for str.strip(unicode) */
12293PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012294_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 void *data;
12297 int kind;
12298 Py_ssize_t i, j, len;
12299 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012300 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12303 return NULL;
12304
12305 kind = PyUnicode_KIND(self);
12306 data = PyUnicode_DATA(self);
12307 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012308 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12310 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012311 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012312
Benjamin Peterson14339b62009-01-31 16:36:08 +000012313 i = 0;
12314 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012315 while (i < len) {
12316 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12317 if (!BLOOM(sepmask, ch))
12318 break;
12319 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12320 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 i++;
12322 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012323 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012324
Benjamin Peterson14339b62009-01-31 16:36:08 +000012325 j = len;
12326 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012327 j--;
12328 while (j >= i) {
12329 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12330 if (!BLOOM(sepmask, ch))
12331 break;
12332 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12333 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012334 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012335 }
12336
Benjamin Peterson29060642009-01-31 22:14:21 +000012337 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012338 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012339
Victor Stinner7931d9a2011-11-04 00:22:48 +010012340 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341}
12342
12343PyObject*
12344PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12345{
12346 unsigned char *data;
12347 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012348 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349
Victor Stinnerde636f32011-10-01 03:55:54 +020012350 if (PyUnicode_READY(self) == -1)
12351 return NULL;
12352
Victor Stinner684d5fd2012-05-03 02:32:34 +020012353 length = PyUnicode_GET_LENGTH(self);
12354 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012355
Victor Stinner684d5fd2012-05-03 02:32:34 +020012356 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012357 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358
Victor Stinnerde636f32011-10-01 03:55:54 +020012359 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012360 PyErr_SetString(PyExc_IndexError, "string index out of range");
12361 return NULL;
12362 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012363 if (start >= length || end < start)
12364 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012365
Victor Stinner684d5fd2012-05-03 02:32:34 +020012366 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012367 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012368 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012369 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012370 }
12371 else {
12372 kind = PyUnicode_KIND(self);
12373 data = PyUnicode_1BYTE_DATA(self);
12374 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012375 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012376 length);
12377 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012379
12380static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012381do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012383 Py_ssize_t len, i, j;
12384
12385 if (PyUnicode_READY(self) == -1)
12386 return NULL;
12387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012389
Victor Stinnercc7af722013-04-09 22:39:24 +020012390 if (PyUnicode_IS_ASCII(self)) {
12391 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12392
12393 i = 0;
12394 if (striptype != RIGHTSTRIP) {
12395 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012396 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012397 if (!_Py_ascii_whitespace[ch])
12398 break;
12399 i++;
12400 }
12401 }
12402
12403 j = len;
12404 if (striptype != LEFTSTRIP) {
12405 j--;
12406 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012407 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012408 if (!_Py_ascii_whitespace[ch])
12409 break;
12410 j--;
12411 }
12412 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012413 }
12414 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012415 else {
12416 int kind = PyUnicode_KIND(self);
12417 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012418
Victor Stinnercc7af722013-04-09 22:39:24 +020012419 i = 0;
12420 if (striptype != RIGHTSTRIP) {
12421 while (i < len) {
12422 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12423 if (!Py_UNICODE_ISSPACE(ch))
12424 break;
12425 i++;
12426 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012427 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012428
12429 j = len;
12430 if (striptype != LEFTSTRIP) {
12431 j--;
12432 while (j >= i) {
12433 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12434 if (!Py_UNICODE_ISSPACE(ch))
12435 break;
12436 j--;
12437 }
12438 j++;
12439 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012440 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012441
Victor Stinner7931d9a2011-11-04 00:22:48 +010012442 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443}
12444
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012445
12446static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012447do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012448{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012449 if (sep != NULL && sep != Py_None) {
12450 if (PyUnicode_Check(sep))
12451 return _PyUnicode_XStrip(self, striptype, sep);
12452 else {
12453 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012454 "%s arg must be None or str",
12455 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012456 return NULL;
12457 }
12458 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012459
Benjamin Peterson14339b62009-01-31 16:36:08 +000012460 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012461}
12462
12463
INADA Naoki3ae20562017-01-16 20:41:20 +090012464/*[clinic input]
12465str.strip as unicode_strip
12466
12467 chars: object = None
12468 /
12469
Victor Stinner0c4a8282017-01-17 02:21:47 +010012470Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012471
12472If chars is given and not None, remove characters in chars instead.
12473[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012474
12475static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012476unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012477/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012478{
INADA Naoki3ae20562017-01-16 20:41:20 +090012479 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012480}
12481
12482
INADA Naoki3ae20562017-01-16 20:41:20 +090012483/*[clinic input]
12484str.lstrip as unicode_lstrip
12485
12486 chars: object = NULL
12487 /
12488
12489Return a copy of the string with leading whitespace removed.
12490
12491If chars is given and not None, remove characters in chars instead.
12492[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012493
12494static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012495unicode_lstrip_impl(PyObject *self, PyObject *chars)
12496/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012497{
INADA Naoki3ae20562017-01-16 20:41:20 +090012498 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012499}
12500
12501
INADA Naoki3ae20562017-01-16 20:41:20 +090012502/*[clinic input]
12503str.rstrip as unicode_rstrip
12504
12505 chars: object = NULL
12506 /
12507
12508Return a copy of the string with trailing whitespace removed.
12509
12510If chars is given and not None, remove characters in chars instead.
12511[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012512
12513static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012514unicode_rstrip_impl(PyObject *self, PyObject *chars)
12515/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012516{
INADA Naoki3ae20562017-01-16 20:41:20 +090012517 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012518}
12519
12520
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012522unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012524 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012525 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526
Serhiy Storchaka05997252013-01-26 12:14:02 +020012527 if (len < 1)
12528 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529
Victor Stinnerc4b49542011-12-11 22:44:26 +010012530 /* no repeat, return original string */
12531 if (len == 1)
12532 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012533
Benjamin Petersonbac79492012-01-14 13:34:47 -050012534 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 return NULL;
12536
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012537 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012538 PyErr_SetString(PyExc_OverflowError,
12539 "repeated string is too long");
12540 return NULL;
12541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012543
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012544 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545 if (!u)
12546 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012547 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 if (PyUnicode_GET_LENGTH(str) == 1) {
12550 const int kind = PyUnicode_KIND(str);
12551 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012552 if (kind == PyUnicode_1BYTE_KIND) {
12553 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012554 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012555 }
12556 else if (kind == PyUnicode_2BYTE_KIND) {
12557 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012558 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012559 ucs2[n] = fill_char;
12560 } else {
12561 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12562 assert(kind == PyUnicode_4BYTE_KIND);
12563 for (n = 0; n < len; ++n)
12564 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012565 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 }
12567 else {
12568 /* number of characters copied this far */
12569 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012570 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012572 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012574 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012576 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012577 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579 }
12580
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012581 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012582 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583}
12584
Alexander Belopolsky40018472011-02-26 01:02:56 +000012585PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012586PyUnicode_Replace(PyObject *str,
12587 PyObject *substr,
12588 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012589 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012591 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12592 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012594 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595}
12596
INADA Naoki3ae20562017-01-16 20:41:20 +090012597/*[clinic input]
12598str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599
INADA Naoki3ae20562017-01-16 20:41:20 +090012600 old: unicode
12601 new: unicode
12602 count: Py_ssize_t = -1
12603 Maximum number of occurrences to replace.
12604 -1 (the default value) means replace all occurrences.
12605 /
12606
12607Return a copy with all occurrences of substring old replaced by new.
12608
12609If the optional argument count is given, only the first count occurrences are
12610replaced.
12611[clinic start generated code]*/
12612
12613static PyObject *
12614unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12615 Py_ssize_t count)
12616/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012618 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012619 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012620 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621}
12622
Alexander Belopolsky40018472011-02-26 01:02:56 +000012623static PyObject *
12624unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012626 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012627 Py_ssize_t isize;
12628 Py_ssize_t osize, squote, dquote, i, o;
12629 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012630 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012633 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012634 return NULL;
12635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 isize = PyUnicode_GET_LENGTH(unicode);
12637 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 /* Compute length of output, quote characters, and
12640 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012641 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642 max = 127;
12643 squote = dquote = 0;
12644 ikind = PyUnicode_KIND(unicode);
12645 for (i = 0; i < isize; i++) {
12646 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012647 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012648 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012649 case '\'': squote++; break;
12650 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012652 incr = 2;
12653 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 default:
12655 /* Fast-path ASCII */
12656 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012657 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012659 ;
12660 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012663 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012665 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012667 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012669 if (osize > PY_SSIZE_T_MAX - incr) {
12670 PyErr_SetString(PyExc_OverflowError,
12671 "string is too long to generate repr");
12672 return NULL;
12673 }
12674 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 }
12676
12677 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012678 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012679 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012680 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 if (dquote)
12682 /* Both squote and dquote present. Use squote,
12683 and escape them */
12684 osize += squote;
12685 else
12686 quote = '"';
12687 }
Victor Stinner55c08782013-04-14 18:45:39 +020012688 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689
12690 repr = PyUnicode_New(osize, max);
12691 if (repr == NULL)
12692 return NULL;
12693 okind = PyUnicode_KIND(repr);
12694 odata = PyUnicode_DATA(repr);
12695
12696 PyUnicode_WRITE(okind, odata, 0, quote);
12697 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012698 if (unchanged) {
12699 _PyUnicode_FastCopyCharacters(repr, 1,
12700 unicode, 0,
12701 isize);
12702 }
12703 else {
12704 for (i = 0, o = 1; i < isize; i++) {
12705 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706
Victor Stinner55c08782013-04-14 18:45:39 +020012707 /* Escape quotes and backslashes */
12708 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012709 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012711 continue;
12712 }
12713
12714 /* Map special whitespace to '\t', \n', '\r' */
12715 if (ch == '\t') {
12716 PyUnicode_WRITE(okind, odata, o++, '\\');
12717 PyUnicode_WRITE(okind, odata, o++, 't');
12718 }
12719 else if (ch == '\n') {
12720 PyUnicode_WRITE(okind, odata, o++, '\\');
12721 PyUnicode_WRITE(okind, odata, o++, 'n');
12722 }
12723 else if (ch == '\r') {
12724 PyUnicode_WRITE(okind, odata, o++, '\\');
12725 PyUnicode_WRITE(okind, odata, o++, 'r');
12726 }
12727
12728 /* Map non-printable US ASCII to '\xhh' */
12729 else if (ch < ' ' || ch == 0x7F) {
12730 PyUnicode_WRITE(okind, odata, o++, '\\');
12731 PyUnicode_WRITE(okind, odata, o++, 'x');
12732 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12733 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12734 }
12735
12736 /* Copy ASCII characters as-is */
12737 else if (ch < 0x7F) {
12738 PyUnicode_WRITE(okind, odata, o++, ch);
12739 }
12740
12741 /* Non-ASCII characters */
12742 else {
12743 /* Map Unicode whitespace and control characters
12744 (categories Z* and C* except ASCII space)
12745 */
12746 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12747 PyUnicode_WRITE(okind, odata, o++, '\\');
12748 /* Map 8-bit characters to '\xhh' */
12749 if (ch <= 0xff) {
12750 PyUnicode_WRITE(okind, odata, o++, 'x');
12751 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12752 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12753 }
12754 /* Map 16-bit characters to '\uxxxx' */
12755 else if (ch <= 0xffff) {
12756 PyUnicode_WRITE(okind, odata, o++, 'u');
12757 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12758 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12759 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12760 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12761 }
12762 /* Map 21-bit characters to '\U00xxxxxx' */
12763 else {
12764 PyUnicode_WRITE(okind, odata, o++, 'U');
12765 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12766 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12767 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12768 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12769 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12770 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12771 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12772 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12773 }
12774 }
12775 /* Copy characters as-is */
12776 else {
12777 PyUnicode_WRITE(okind, odata, o++, ch);
12778 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012779 }
12780 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012781 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012782 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012783 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012784 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785}
12786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012787PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012788 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789\n\
12790Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012791such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792arguments start and end are interpreted as in slice notation.\n\
12793\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012794Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795
12796static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012797unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012799 /* initialize variables to prevent gcc warning */
12800 PyObject *substring = NULL;
12801 Py_ssize_t start = 0;
12802 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012803 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012805 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012806 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012808 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012811 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 if (result == -2)
12814 return NULL;
12815
Christian Heimes217cfd12007-12-02 14:31:20 +000012816 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817}
12818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012819PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012822Return the highest index in S where substring sub is found,\n\
12823such that sub is contained within S[start:end]. Optional\n\
12824arguments start and end are interpreted as in slice notation.\n\
12825\n\
12826Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827
12828static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012831 /* initialize variables to prevent gcc warning */
12832 PyObject *substring = NULL;
12833 Py_ssize_t start = 0;
12834 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012835 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012836
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012837 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012838 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012840 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012843 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 if (result == -2)
12846 return NULL;
12847
Guido van Rossumd57fd912000-03-10 22:53:23 +000012848 if (result < 0) {
12849 PyErr_SetString(PyExc_ValueError, "substring not found");
12850 return NULL;
12851 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012852
Christian Heimes217cfd12007-12-02 14:31:20 +000012853 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012854}
12855
INADA Naoki3ae20562017-01-16 20:41:20 +090012856/*[clinic input]
12857str.rjust as unicode_rjust
12858
12859 width: Py_ssize_t
12860 fillchar: Py_UCS4 = ' '
12861 /
12862
12863Return a right-justified string of length width.
12864
12865Padding is done using the specified fill character (default is a space).
12866[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867
12868static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012869unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12870/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012872 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012873 return NULL;
12874
Victor Stinnerc4b49542011-12-11 22:44:26 +010012875 if (PyUnicode_GET_LENGTH(self) >= width)
12876 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877
Victor Stinnerc4b49542011-12-11 22:44:26 +010012878 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012879}
12880
Alexander Belopolsky40018472011-02-26 01:02:56 +000012881PyObject *
12882PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012884 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012887 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888}
12889
INADA Naoki3ae20562017-01-16 20:41:20 +090012890/*[clinic input]
12891str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892
INADA Naoki3ae20562017-01-16 20:41:20 +090012893 sep: object = None
12894 The delimiter according which to split the string.
12895 None (the default value) means split according to any whitespace,
12896 and discard empty strings from the result.
12897 maxsplit: Py_ssize_t = -1
12898 Maximum number of splits to do.
12899 -1 (the default value) means no limit.
12900
12901Return a list of the words in the string, using sep as the delimiter string.
12902[clinic start generated code]*/
12903
12904static PyObject *
12905unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12906/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907{
INADA Naoki3ae20562017-01-16 20:41:20 +090012908 if (sep == Py_None)
12909 return split(self, NULL, maxsplit);
12910 if (PyUnicode_Check(sep))
12911 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012912
12913 PyErr_Format(PyExc_TypeError,
12914 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012915 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012917}
12918
Thomas Wouters477c8d52006-05-27 19:21:47 +000012919PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012920PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012921{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012922 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012923 int kind1, kind2;
12924 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012925 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012926
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012927 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012928 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012929
Victor Stinner14f8f022011-10-05 20:58:25 +020012930 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012931 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012932 len1 = PyUnicode_GET_LENGTH(str_obj);
12933 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012934 if (kind1 < kind2 || len1 < len2) {
12935 _Py_INCREF_UNICODE_EMPTY();
12936 if (!unicode_empty)
12937 out = NULL;
12938 else {
12939 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12940 Py_DECREF(unicode_empty);
12941 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012942 return out;
12943 }
12944 buf1 = PyUnicode_DATA(str_obj);
12945 buf2 = PyUnicode_DATA(sep_obj);
12946 if (kind2 != kind1) {
12947 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12948 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012949 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012952 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012953 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012954 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12955 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12956 else
12957 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012958 break;
12959 case PyUnicode_2BYTE_KIND:
12960 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12961 break;
12962 case PyUnicode_4BYTE_KIND:
12963 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12964 break;
12965 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012966 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012967 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012968
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012969 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012970 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012971
12972 return out;
12973}
12974
12975
12976PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012977PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012979 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012980 int kind1, kind2;
12981 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012983
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012984 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012985 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012986
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012987 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012988 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012989 len1 = PyUnicode_GET_LENGTH(str_obj);
12990 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012991 if (kind1 < kind2 || len1 < len2) {
12992 _Py_INCREF_UNICODE_EMPTY();
12993 if (!unicode_empty)
12994 out = NULL;
12995 else {
12996 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12997 Py_DECREF(unicode_empty);
12998 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012999 return out;
13000 }
13001 buf1 = PyUnicode_DATA(str_obj);
13002 buf2 = PyUnicode_DATA(sep_obj);
13003 if (kind2 != kind1) {
13004 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13005 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013006 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013007 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013009 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013011 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13012 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13013 else
13014 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013015 break;
13016 case PyUnicode_2BYTE_KIND:
13017 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13018 break;
13019 case PyUnicode_4BYTE_KIND:
13020 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13021 break;
13022 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013023 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013024 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013025
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013026 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013027 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013028
13029 return out;
13030}
13031
INADA Naoki3ae20562017-01-16 20:41:20 +090013032/*[clinic input]
13033str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013034
INADA Naoki3ae20562017-01-16 20:41:20 +090013035 sep: object
13036 /
13037
13038Partition the string into three parts using the given separator.
13039
13040This will search for the separator in the string. If the separator is found,
13041returns a 3-tuple containing the part before the separator, the separator
13042itself, and the part after it.
13043
13044If the separator is not found, returns a 3-tuple containing the original string
13045and two empty strings.
13046[clinic start generated code]*/
13047
13048static PyObject *
13049unicode_partition(PyObject *self, PyObject *sep)
13050/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013051{
INADA Naoki3ae20562017-01-16 20:41:20 +090013052 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013053}
13054
INADA Naoki3ae20562017-01-16 20:41:20 +090013055/*[clinic input]
13056str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013057
INADA Naoki3ae20562017-01-16 20:41:20 +090013058Partition the string into three parts using the given separator.
13059
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013060This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013061the separator is found, returns a 3-tuple containing the part before the
13062separator, the separator itself, and the part after it.
13063
13064If the separator is not found, returns a 3-tuple containing two empty strings
13065and the original string.
13066[clinic start generated code]*/
13067
13068static PyObject *
13069unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013070/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013071{
INADA Naoki3ae20562017-01-16 20:41:20 +090013072 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013073}
13074
Alexander Belopolsky40018472011-02-26 01:02:56 +000013075PyObject *
13076PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013077{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013078 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013079 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013080
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013081 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013082}
13083
INADA Naoki3ae20562017-01-16 20:41:20 +090013084/*[clinic input]
13085str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013086
INADA Naoki3ae20562017-01-16 20:41:20 +090013087Return a list of the words in the string, using sep as the delimiter string.
13088
13089Splits are done starting at the end of the string and working to the front.
13090[clinic start generated code]*/
13091
13092static PyObject *
13093unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13094/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013095{
INADA Naoki3ae20562017-01-16 20:41:20 +090013096 if (sep == Py_None)
13097 return rsplit(self, NULL, maxsplit);
13098 if (PyUnicode_Check(sep))
13099 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013100
13101 PyErr_Format(PyExc_TypeError,
13102 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013103 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013104 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013105}
13106
INADA Naoki3ae20562017-01-16 20:41:20 +090013107/*[clinic input]
13108str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013110 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013111
13112Return a list of the lines in the string, breaking at line boundaries.
13113
13114Line breaks are not included in the resulting list unless keepends is given and
13115true.
13116[clinic start generated code]*/
13117
13118static PyObject *
13119unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013120/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013122 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123}
13124
13125static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013126PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013128 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129}
13130
INADA Naoki3ae20562017-01-16 20:41:20 +090013131/*[clinic input]
13132str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133
INADA Naoki3ae20562017-01-16 20:41:20 +090013134Convert uppercase characters to lowercase and lowercase characters to uppercase.
13135[clinic start generated code]*/
13136
13137static PyObject *
13138unicode_swapcase_impl(PyObject *self)
13139/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013141 if (PyUnicode_READY(self) == -1)
13142 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013143 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013144}
13145
Larry Hastings61272b72014-01-07 12:41:53 -080013146/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013147
Larry Hastings31826802013-10-19 00:09:25 -070013148@staticmethod
13149str.maketrans as unicode_maketrans
13150
13151 x: object
13152
13153 y: unicode=NULL
13154
13155 z: unicode=NULL
13156
13157 /
13158
13159Return a translation table usable for str.translate().
13160
13161If there is only one argument, it must be a dictionary mapping Unicode
13162ordinals (integers) or characters to Unicode ordinals, strings or None.
13163Character keys will be then converted to ordinals.
13164If there are two arguments, they must be strings of equal length, and
13165in the resulting dictionary, each character in x will be mapped to the
13166character at the same position in y. If there is a third argument, it
13167must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013168[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013169
Larry Hastings31826802013-10-19 00:09:25 -070013170static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013171unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013172/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013173{
Georg Brandlceee0772007-11-27 23:48:05 +000013174 PyObject *new = NULL, *key, *value;
13175 Py_ssize_t i = 0;
13176 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013177
Georg Brandlceee0772007-11-27 23:48:05 +000013178 new = PyDict_New();
13179 if (!new)
13180 return NULL;
13181 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013182 int x_kind, y_kind, z_kind;
13183 void *x_data, *y_data, *z_data;
13184
Georg Brandlceee0772007-11-27 23:48:05 +000013185 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013186 if (!PyUnicode_Check(x)) {
13187 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13188 "be a string if there is a second argument");
13189 goto err;
13190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013191 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013192 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13193 "arguments must have equal length");
13194 goto err;
13195 }
13196 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013197 x_kind = PyUnicode_KIND(x);
13198 y_kind = PyUnicode_KIND(y);
13199 x_data = PyUnicode_DATA(x);
13200 y_data = PyUnicode_DATA(y);
13201 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13202 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013203 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013204 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013205 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013206 if (!value) {
13207 Py_DECREF(key);
13208 goto err;
13209 }
Georg Brandlceee0772007-11-27 23:48:05 +000013210 res = PyDict_SetItem(new, key, value);
13211 Py_DECREF(key);
13212 Py_DECREF(value);
13213 if (res < 0)
13214 goto err;
13215 }
13216 /* create entries for deleting chars in z */
13217 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 z_kind = PyUnicode_KIND(z);
13219 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013220 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013221 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013222 if (!key)
13223 goto err;
13224 res = PyDict_SetItem(new, key, Py_None);
13225 Py_DECREF(key);
13226 if (res < 0)
13227 goto err;
13228 }
13229 }
13230 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013231 int kind;
13232 void *data;
13233
Georg Brandlceee0772007-11-27 23:48:05 +000013234 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013235 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013236 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13237 "to maketrans it must be a dict");
13238 goto err;
13239 }
13240 /* copy entries into the new dict, converting string keys to int keys */
13241 while (PyDict_Next(x, &i, &key, &value)) {
13242 if (PyUnicode_Check(key)) {
13243 /* convert string keys to integer keys */
13244 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013245 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013246 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13247 "table must be of length 1");
13248 goto err;
13249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013250 kind = PyUnicode_KIND(key);
13251 data = PyUnicode_DATA(key);
13252 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013253 if (!newkey)
13254 goto err;
13255 res = PyDict_SetItem(new, newkey, value);
13256 Py_DECREF(newkey);
13257 if (res < 0)
13258 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013259 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013260 /* just keep integer keys */
13261 if (PyDict_SetItem(new, key, value) < 0)
13262 goto err;
13263 } else {
13264 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13265 "be strings or integers");
13266 goto err;
13267 }
13268 }
13269 }
13270 return new;
13271 err:
13272 Py_DECREF(new);
13273 return NULL;
13274}
13275
INADA Naoki3ae20562017-01-16 20:41:20 +090013276/*[clinic input]
13277str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013278
INADA Naoki3ae20562017-01-16 20:41:20 +090013279 table: object
13280 Translation table, which must be a mapping of Unicode ordinals to
13281 Unicode ordinals, strings, or None.
13282 /
13283
13284Replace each character in the string using the given translation table.
13285
13286The table must implement lookup/indexing via __getitem__, for instance a
13287dictionary or list. If this operation raises LookupError, the character is
13288left untouched. Characters mapped to None are deleted.
13289[clinic start generated code]*/
13290
13291static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013292unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013293/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013295 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013296}
13297
INADA Naoki3ae20562017-01-16 20:41:20 +090013298/*[clinic input]
13299str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013300
INADA Naoki3ae20562017-01-16 20:41:20 +090013301Return a copy of the string converted to uppercase.
13302[clinic start generated code]*/
13303
13304static PyObject *
13305unicode_upper_impl(PyObject *self)
13306/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013307{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013308 if (PyUnicode_READY(self) == -1)
13309 return NULL;
13310 if (PyUnicode_IS_ASCII(self))
13311 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013312 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013313}
13314
INADA Naoki3ae20562017-01-16 20:41:20 +090013315/*[clinic input]
13316str.zfill as unicode_zfill
13317
13318 width: Py_ssize_t
13319 /
13320
13321Pad a numeric string with zeros on the left, to fill a field of the given width.
13322
13323The string is never truncated.
13324[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013325
13326static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013327unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013328/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013329{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013330 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013331 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013332 int kind;
13333 void *data;
13334 Py_UCS4 chr;
13335
Benjamin Petersonbac79492012-01-14 13:34:47 -050013336 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013337 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338
Victor Stinnerc4b49542011-12-11 22:44:26 +010013339 if (PyUnicode_GET_LENGTH(self) >= width)
13340 return unicode_result_unchanged(self);
13341
13342 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343
13344 u = pad(self, fill, 0, '0');
13345
Walter Dörwald068325e2002-04-15 13:36:47 +000013346 if (u == NULL)
13347 return NULL;
13348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013349 kind = PyUnicode_KIND(u);
13350 data = PyUnicode_DATA(u);
13351 chr = PyUnicode_READ(kind, data, fill);
13352
13353 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013355 PyUnicode_WRITE(kind, data, 0, chr);
13356 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013357 }
13358
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013359 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013360 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013362
13363#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013364static PyObject *
13365unicode__decimal2ascii(PyObject *self)
13366{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013367 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013368}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013369#endif
13370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013371PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013372 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013373\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013374Return True if S starts with the specified prefix, False otherwise.\n\
13375With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013376With optional end, stop comparing S at that position.\n\
13377prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013378
13379static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013380unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013382{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013383 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013384 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013385 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013386 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013387 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388
Jesus Ceaac451502011-04-20 17:09:23 +020013389 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013390 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013391 if (PyTuple_Check(subobj)) {
13392 Py_ssize_t i;
13393 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013394 substring = PyTuple_GET_ITEM(subobj, i);
13395 if (!PyUnicode_Check(substring)) {
13396 PyErr_Format(PyExc_TypeError,
13397 "tuple for startswith must only contain str, "
13398 "not %.100s",
13399 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013400 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013401 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013402 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013403 if (result == -1)
13404 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013405 if (result) {
13406 Py_RETURN_TRUE;
13407 }
13408 }
13409 /* nothing matched */
13410 Py_RETURN_FALSE;
13411 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013412 if (!PyUnicode_Check(subobj)) {
13413 PyErr_Format(PyExc_TypeError,
13414 "startswith first arg must be str or "
13415 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013417 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013418 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013419 if (result == -1)
13420 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013421 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422}
13423
13424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013425PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013427\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013428Return True if S ends with the specified suffix, False otherwise.\n\
13429With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013430With optional end, stop comparing S at that position.\n\
13431suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432
13433static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013434unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013435 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013436{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013437 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013438 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013439 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013440 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013441 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013442
Jesus Ceaac451502011-04-20 17:09:23 +020013443 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013444 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013445 if (PyTuple_Check(subobj)) {
13446 Py_ssize_t i;
13447 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013448 substring = PyTuple_GET_ITEM(subobj, i);
13449 if (!PyUnicode_Check(substring)) {
13450 PyErr_Format(PyExc_TypeError,
13451 "tuple for endswith must only contain str, "
13452 "not %.100s",
13453 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013455 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013456 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013457 if (result == -1)
13458 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013459 if (result) {
13460 Py_RETURN_TRUE;
13461 }
13462 }
13463 Py_RETURN_FALSE;
13464 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013465 if (!PyUnicode_Check(subobj)) {
13466 PyErr_Format(PyExc_TypeError,
13467 "endswith first arg must be str or "
13468 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013469 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013470 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013471 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013472 if (result == -1)
13473 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013474 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013475}
13476
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013477static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013478_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013479{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013480 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13481 writer->data = PyUnicode_DATA(writer->buffer);
13482
13483 if (!writer->readonly) {
13484 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013485 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013486 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013487 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013488 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13489 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13490 writer->kind = PyUnicode_WCHAR_KIND;
13491 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13492
Victor Stinner8f674cc2013-04-17 23:02:17 +020013493 /* Copy-on-write mode: set buffer size to 0 so
13494 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13495 * next write. */
13496 writer->size = 0;
13497 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013498}
13499
Victor Stinnerd3f08822012-05-29 12:57:52 +020013500void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013501_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013502{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013503 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013504
13505 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013506 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013507
13508 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13509 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13510 writer->kind = PyUnicode_WCHAR_KIND;
13511 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013512}
13513
Victor Stinnerd3f08822012-05-29 12:57:52 +020013514int
13515_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13516 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013517{
13518 Py_ssize_t newlen;
13519 PyObject *newbuffer;
13520
Victor Stinner2740e462016-09-06 16:58:36 -070013521 assert(maxchar <= MAX_UNICODE);
13522
Victor Stinnerca9381e2015-09-22 00:58:32 +020013523 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013524 assert((maxchar > writer->maxchar && length >= 0)
13525 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013526
Victor Stinner202fdca2012-05-07 12:47:02 +020013527 if (length > PY_SSIZE_T_MAX - writer->pos) {
13528 PyErr_NoMemory();
13529 return -1;
13530 }
13531 newlen = writer->pos + length;
13532
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013533 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013534
Victor Stinnerd3f08822012-05-29 12:57:52 +020013535 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013536 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013537 if (writer->overallocate
13538 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13539 /* overallocate to limit the number of realloc() */
13540 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013541 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013542 if (newlen < writer->min_length)
13543 newlen = writer->min_length;
13544
Victor Stinnerd3f08822012-05-29 12:57:52 +020013545 writer->buffer = PyUnicode_New(newlen, maxchar);
13546 if (writer->buffer == NULL)
13547 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013548 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013549 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013550 if (writer->overallocate
13551 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13552 /* overallocate to limit the number of realloc() */
13553 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013554 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013555 if (newlen < writer->min_length)
13556 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013557
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013558 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013559 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013560 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013561 newbuffer = PyUnicode_New(newlen, maxchar);
13562 if (newbuffer == NULL)
13563 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013564 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13565 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013566 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013567 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013568 }
13569 else {
13570 newbuffer = resize_compact(writer->buffer, newlen);
13571 if (newbuffer == NULL)
13572 return -1;
13573 }
13574 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013575 }
13576 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013577 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013578 newbuffer = PyUnicode_New(writer->size, maxchar);
13579 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013580 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013581 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13582 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013583 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013584 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013585 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013586 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013587
13588#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013589}
13590
Victor Stinnerca9381e2015-09-22 00:58:32 +020013591int
13592_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13593 enum PyUnicode_Kind kind)
13594{
13595 Py_UCS4 maxchar;
13596
13597 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13598 assert(writer->kind < kind);
13599
13600 switch (kind)
13601 {
13602 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13603 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13604 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13605 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013606 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013607 }
13608
13609 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13610}
13611
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013612static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013613_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013614{
Victor Stinner2740e462016-09-06 16:58:36 -070013615 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013616 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13617 return -1;
13618 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13619 writer->pos++;
13620 return 0;
13621}
13622
13623int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013624_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13625{
13626 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13627}
13628
13629int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013630_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13631{
13632 Py_UCS4 maxchar;
13633 Py_ssize_t len;
13634
13635 if (PyUnicode_READY(str) == -1)
13636 return -1;
13637 len = PyUnicode_GET_LENGTH(str);
13638 if (len == 0)
13639 return 0;
13640 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13641 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013642 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013643 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013644 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013645 Py_INCREF(str);
13646 writer->buffer = str;
13647 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013648 writer->pos += len;
13649 return 0;
13650 }
13651 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13652 return -1;
13653 }
13654 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13655 str, 0, len);
13656 writer->pos += len;
13657 return 0;
13658}
13659
Victor Stinnere215d962012-10-06 23:03:36 +020013660int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013661_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13662 Py_ssize_t start, Py_ssize_t end)
13663{
13664 Py_UCS4 maxchar;
13665 Py_ssize_t len;
13666
13667 if (PyUnicode_READY(str) == -1)
13668 return -1;
13669
13670 assert(0 <= start);
13671 assert(end <= PyUnicode_GET_LENGTH(str));
13672 assert(start <= end);
13673
13674 if (end == 0)
13675 return 0;
13676
13677 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13678 return _PyUnicodeWriter_WriteStr(writer, str);
13679
13680 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13681 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13682 else
13683 maxchar = writer->maxchar;
13684 len = end - start;
13685
13686 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13687 return -1;
13688
13689 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13690 str, start, len);
13691 writer->pos += len;
13692 return 0;
13693}
13694
13695int
Victor Stinner4a587072013-11-19 12:54:53 +010013696_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13697 const char *ascii, Py_ssize_t len)
13698{
13699 if (len == -1)
13700 len = strlen(ascii);
13701
13702 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13703
13704 if (writer->buffer == NULL && !writer->overallocate) {
13705 PyObject *str;
13706
13707 str = _PyUnicode_FromASCII(ascii, len);
13708 if (str == NULL)
13709 return -1;
13710
13711 writer->readonly = 1;
13712 writer->buffer = str;
13713 _PyUnicodeWriter_Update(writer);
13714 writer->pos += len;
13715 return 0;
13716 }
13717
13718 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13719 return -1;
13720
13721 switch (writer->kind)
13722 {
13723 case PyUnicode_1BYTE_KIND:
13724 {
13725 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13726 Py_UCS1 *data = writer->data;
13727
Christian Heimesf051e432016-09-13 20:22:02 +020013728 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013729 break;
13730 }
13731 case PyUnicode_2BYTE_KIND:
13732 {
13733 _PyUnicode_CONVERT_BYTES(
13734 Py_UCS1, Py_UCS2,
13735 ascii, ascii + len,
13736 (Py_UCS2 *)writer->data + writer->pos);
13737 break;
13738 }
13739 case PyUnicode_4BYTE_KIND:
13740 {
13741 _PyUnicode_CONVERT_BYTES(
13742 Py_UCS1, Py_UCS4,
13743 ascii, ascii + len,
13744 (Py_UCS4 *)writer->data + writer->pos);
13745 break;
13746 }
13747 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013748 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013749 }
13750
13751 writer->pos += len;
13752 return 0;
13753}
13754
13755int
13756_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13757 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013758{
13759 Py_UCS4 maxchar;
13760
13761 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13762 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13763 return -1;
13764 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13765 writer->pos += len;
13766 return 0;
13767}
13768
Victor Stinnerd3f08822012-05-29 12:57:52 +020013769PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013770_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013771{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013772 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013773
Victor Stinnerd3f08822012-05-29 12:57:52 +020013774 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013775 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013776 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013777 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013778
13779 str = writer->buffer;
13780 writer->buffer = NULL;
13781
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013782 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013783 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13784 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013785 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013786
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013787 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13788 PyObject *str2;
13789 str2 = resize_compact(str, writer->pos);
13790 if (str2 == NULL) {
13791 Py_DECREF(str);
13792 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013793 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013794 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013795 }
13796
Victor Stinner15a0bd32013-07-08 22:29:55 +020013797 assert(_PyUnicode_CheckConsistency(str, 1));
13798 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013799}
13800
Victor Stinnerd3f08822012-05-29 12:57:52 +020013801void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013802_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013803{
13804 Py_CLEAR(writer->buffer);
13805}
13806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013807#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013808
13809PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013810 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013811\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013812Return a formatted version of S, using substitutions from args and kwargs.\n\
13813The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013814
Eric Smith27bbca62010-11-04 17:06:58 +000013815PyDoc_STRVAR(format_map__doc__,
13816 "S.format_map(mapping) -> str\n\
13817\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013818Return a formatted version of S, using substitutions from mapping.\n\
13819The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013820
INADA Naoki3ae20562017-01-16 20:41:20 +090013821/*[clinic input]
13822str.__format__ as unicode___format__
13823
13824 format_spec: unicode
13825 /
13826
13827Return a formatted version of the string as described by format_spec.
13828[clinic start generated code]*/
13829
Eric Smith4a7d76d2008-05-30 18:10:19 +000013830static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013831unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013832/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013833{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013834 _PyUnicodeWriter writer;
13835 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013836
Victor Stinnerd3f08822012-05-29 12:57:52 +020013837 if (PyUnicode_READY(self) == -1)
13838 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013839 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013840 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13841 self, format_spec, 0,
13842 PyUnicode_GET_LENGTH(format_spec));
13843 if (ret == -1) {
13844 _PyUnicodeWriter_Dealloc(&writer);
13845 return NULL;
13846 }
13847 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013848}
13849
INADA Naoki3ae20562017-01-16 20:41:20 +090013850/*[clinic input]
13851str.__sizeof__ as unicode_sizeof
13852
13853Return the size of the string in memory, in bytes.
13854[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013855
13856static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013857unicode_sizeof_impl(PyObject *self)
13858/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013859{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013860 Py_ssize_t size;
13861
13862 /* If it's a compact object, account for base structure +
13863 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013864 if (PyUnicode_IS_COMPACT_ASCII(self))
13865 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13866 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013867 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013868 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013869 else {
13870 /* If it is a two-block object, account for base object, and
13871 for character block if present. */
13872 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013873 if (_PyUnicode_DATA_ANY(self))
13874 size += (PyUnicode_GET_LENGTH(self) + 1) *
13875 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013876 }
13877 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013878 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013879 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13880 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13881 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13882 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013883
13884 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013885}
13886
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013887static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013888unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013889{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013890 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013891 if (!copy)
13892 return NULL;
13893 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013894}
13895
Guido van Rossumd57fd912000-03-10 22:53:23 +000013896static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013897 UNICODE_ENCODE_METHODDEF
13898 UNICODE_REPLACE_METHODDEF
13899 UNICODE_SPLIT_METHODDEF
13900 UNICODE_RSPLIT_METHODDEF
13901 UNICODE_JOIN_METHODDEF
13902 UNICODE_CAPITALIZE_METHODDEF
13903 UNICODE_CASEFOLD_METHODDEF
13904 UNICODE_TITLE_METHODDEF
13905 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013906 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013907 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013908 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013909 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013910 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013911 UNICODE_LJUST_METHODDEF
13912 UNICODE_LOWER_METHODDEF
13913 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013914 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13915 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013916 UNICODE_RJUST_METHODDEF
13917 UNICODE_RSTRIP_METHODDEF
13918 UNICODE_RPARTITION_METHODDEF
13919 UNICODE_SPLITLINES_METHODDEF
13920 UNICODE_STRIP_METHODDEF
13921 UNICODE_SWAPCASE_METHODDEF
13922 UNICODE_TRANSLATE_METHODDEF
13923 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013924 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13925 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013926 UNICODE_ISLOWER_METHODDEF
13927 UNICODE_ISUPPER_METHODDEF
13928 UNICODE_ISTITLE_METHODDEF
13929 UNICODE_ISSPACE_METHODDEF
13930 UNICODE_ISDECIMAL_METHODDEF
13931 UNICODE_ISDIGIT_METHODDEF
13932 UNICODE_ISNUMERIC_METHODDEF
13933 UNICODE_ISALPHA_METHODDEF
13934 UNICODE_ISALNUM_METHODDEF
13935 UNICODE_ISIDENTIFIER_METHODDEF
13936 UNICODE_ISPRINTABLE_METHODDEF
13937 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013938 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013939 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013940 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013941 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013942 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013943#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013944 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013945 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013946#endif
13947
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013949 {NULL, NULL}
13950};
13951
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013952static PyObject *
13953unicode_mod(PyObject *v, PyObject *w)
13954{
Brian Curtindfc80e32011-08-10 20:28:54 -050013955 if (!PyUnicode_Check(v))
13956 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013957 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013958}
13959
13960static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 0, /*nb_add*/
13962 0, /*nb_subtract*/
13963 0, /*nb_multiply*/
13964 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013965};
13966
Guido van Rossumd57fd912000-03-10 22:53:23 +000013967static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013968 (lenfunc) unicode_length, /* sq_length */
13969 PyUnicode_Concat, /* sq_concat */
13970 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13971 (ssizeargfunc) unicode_getitem, /* sq_item */
13972 0, /* sq_slice */
13973 0, /* sq_ass_item */
13974 0, /* sq_ass_slice */
13975 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013976};
13977
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013978static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013979unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013980{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013981 if (PyUnicode_READY(self) == -1)
13982 return NULL;
13983
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013984 if (PyIndex_Check(item)) {
13985 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013986 if (i == -1 && PyErr_Occurred())
13987 return NULL;
13988 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013989 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013990 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013991 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013992 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013993 PyObject *result;
13994 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013995 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013996 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013997
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013998 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013999 return NULL;
14000 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014001 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14002 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014003
14004 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014005 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014006 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014007 slicelength == PyUnicode_GET_LENGTH(self)) {
14008 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014009 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014010 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014011 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014012 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014013 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014014 src_kind = PyUnicode_KIND(self);
14015 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014016 if (!PyUnicode_IS_ASCII(self)) {
14017 kind_limit = kind_maxchar_limit(src_kind);
14018 max_char = 0;
14019 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14020 ch = PyUnicode_READ(src_kind, src_data, cur);
14021 if (ch > max_char) {
14022 max_char = ch;
14023 if (max_char >= kind_limit)
14024 break;
14025 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014026 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014027 }
Victor Stinner55c99112011-10-13 01:17:06 +020014028 else
14029 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014030 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014031 if (result == NULL)
14032 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014033 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014034 dest_data = PyUnicode_DATA(result);
14035
14036 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014037 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14038 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014039 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014040 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014041 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014042 } else {
14043 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14044 return NULL;
14045 }
14046}
14047
14048static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014049 (lenfunc)unicode_length, /* mp_length */
14050 (binaryfunc)unicode_subscript, /* mp_subscript */
14051 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014052};
14053
Guido van Rossumd57fd912000-03-10 22:53:23 +000014054
Guido van Rossumd57fd912000-03-10 22:53:23 +000014055/* Helpers for PyUnicode_Format() */
14056
Victor Stinnera47082312012-10-04 02:19:54 +020014057struct unicode_formatter_t {
14058 PyObject *args;
14059 int args_owned;
14060 Py_ssize_t arglen, argidx;
14061 PyObject *dict;
14062
14063 enum PyUnicode_Kind fmtkind;
14064 Py_ssize_t fmtcnt, fmtpos;
14065 void *fmtdata;
14066 PyObject *fmtstr;
14067
14068 _PyUnicodeWriter writer;
14069};
14070
14071struct unicode_format_arg_t {
14072 Py_UCS4 ch;
14073 int flags;
14074 Py_ssize_t width;
14075 int prec;
14076 int sign;
14077};
14078
Guido van Rossumd57fd912000-03-10 22:53:23 +000014079static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014080unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014081{
Victor Stinnera47082312012-10-04 02:19:54 +020014082 Py_ssize_t argidx = ctx->argidx;
14083
14084 if (argidx < ctx->arglen) {
14085 ctx->argidx++;
14086 if (ctx->arglen < 0)
14087 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014088 else
Victor Stinnera47082312012-10-04 02:19:54 +020014089 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014090 }
14091 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014092 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014093 return NULL;
14094}
14095
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014096/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014097
Victor Stinnera47082312012-10-04 02:19:54 +020014098/* Format a float into the writer if the writer is not NULL, or into *p_output
14099 otherwise.
14100
14101 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014102static int
Victor Stinnera47082312012-10-04 02:19:54 +020014103formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14104 PyObject **p_output,
14105 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014106{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014107 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014108 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014109 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014110 int prec;
14111 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014112
Guido van Rossumd57fd912000-03-10 22:53:23 +000014113 x = PyFloat_AsDouble(v);
14114 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014115 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014116
Victor Stinnera47082312012-10-04 02:19:54 +020014117 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014118 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014119 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014120
Victor Stinnera47082312012-10-04 02:19:54 +020014121 if (arg->flags & F_ALT)
14122 dtoa_flags = Py_DTSF_ALT;
14123 else
14124 dtoa_flags = 0;
14125 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014126 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014127 return -1;
14128 len = strlen(p);
14129 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014130 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014131 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014132 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014133 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014134 }
14135 else
14136 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014137 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014138 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014139}
14140
Victor Stinnerd0880d52012-04-27 23:40:13 +020014141/* formatlong() emulates the format codes d, u, o, x and X, and
14142 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14143 * Python's regular ints.
14144 * Return value: a new PyUnicodeObject*, or NULL if error.
14145 * The output string is of the form
14146 * "-"? ("0x" | "0X")? digit+
14147 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14148 * set in flags. The case of hex digits will be correct,
14149 * There will be at least prec digits, zero-filled on the left if
14150 * necessary to get that many.
14151 * val object to be converted
14152 * flags bitmask of format flags; only F_ALT is looked at
14153 * prec minimum number of digits; 0-fill on left if needed
14154 * type a character in [duoxX]; u acts the same as d
14155 *
14156 * CAUTION: o, x and X conversions on regular ints can never
14157 * produce a '-' sign, but can for Python's unbounded ints.
14158 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014159PyObject *
14160_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014161{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014162 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014163 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014164 Py_ssize_t i;
14165 int sign; /* 1 if '-', else 0 */
14166 int len; /* number of characters */
14167 Py_ssize_t llen;
14168 int numdigits; /* len == numnondigits + numdigits */
14169 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014170
Victor Stinnerd0880d52012-04-27 23:40:13 +020014171 /* Avoid exceeding SSIZE_T_MAX */
14172 if (prec > INT_MAX-3) {
14173 PyErr_SetString(PyExc_OverflowError,
14174 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014175 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014176 }
14177
14178 assert(PyLong_Check(val));
14179
14180 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014181 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014182 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014183 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014184 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014185 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014186 /* int and int subclasses should print numerically when a numeric */
14187 /* format code is used (see issue18780) */
14188 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014189 break;
14190 case 'o':
14191 numnondigits = 2;
14192 result = PyNumber_ToBase(val, 8);
14193 break;
14194 case 'x':
14195 case 'X':
14196 numnondigits = 2;
14197 result = PyNumber_ToBase(val, 16);
14198 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014199 }
14200 if (!result)
14201 return NULL;
14202
14203 assert(unicode_modifiable(result));
14204 assert(PyUnicode_IS_READY(result));
14205 assert(PyUnicode_IS_ASCII(result));
14206
14207 /* To modify the string in-place, there can only be one reference. */
14208 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014209 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014210 PyErr_BadInternalCall();
14211 return NULL;
14212 }
14213 buf = PyUnicode_DATA(result);
14214 llen = PyUnicode_GET_LENGTH(result);
14215 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014216 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014217 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014218 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014219 return NULL;
14220 }
14221 len = (int)llen;
14222 sign = buf[0] == '-';
14223 numnondigits += sign;
14224 numdigits = len - numnondigits;
14225 assert(numdigits > 0);
14226
14227 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014228 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014229 (type == 'o' || type == 'x' || type == 'X'))) {
14230 assert(buf[sign] == '0');
14231 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14232 buf[sign+1] == 'o');
14233 numnondigits -= 2;
14234 buf += 2;
14235 len -= 2;
14236 if (sign)
14237 buf[0] = '-';
14238 assert(len == numnondigits + numdigits);
14239 assert(numdigits > 0);
14240 }
14241
14242 /* Fill with leading zeroes to meet minimum width. */
14243 if (prec > numdigits) {
14244 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14245 numnondigits + prec);
14246 char *b1;
14247 if (!r1) {
14248 Py_DECREF(result);
14249 return NULL;
14250 }
14251 b1 = PyBytes_AS_STRING(r1);
14252 for (i = 0; i < numnondigits; ++i)
14253 *b1++ = *buf++;
14254 for (i = 0; i < prec - numdigits; i++)
14255 *b1++ = '0';
14256 for (i = 0; i < numdigits; i++)
14257 *b1++ = *buf++;
14258 *b1 = '\0';
14259 Py_DECREF(result);
14260 result = r1;
14261 buf = PyBytes_AS_STRING(result);
14262 len = numnondigits + prec;
14263 }
14264
14265 /* Fix up case for hex conversions. */
14266 if (type == 'X') {
14267 /* Need to convert all lower case letters to upper case.
14268 and need to convert 0x to 0X (and -0x to -0X). */
14269 for (i = 0; i < len; i++)
14270 if (buf[i] >= 'a' && buf[i] <= 'x')
14271 buf[i] -= 'a'-'A';
14272 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014273 if (!PyUnicode_Check(result)
14274 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014275 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014276 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014277 Py_DECREF(result);
14278 result = unicode;
14279 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014280 else if (len != PyUnicode_GET_LENGTH(result)) {
14281 if (PyUnicode_Resize(&result, len) < 0)
14282 Py_CLEAR(result);
14283 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014285}
14286
Ethan Furmandf3ed242014-01-05 06:50:30 -080014287/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014288 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014289 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014290 * -1 and raise an exception on error */
14291static int
Victor Stinnera47082312012-10-04 02:19:54 +020014292mainformatlong(PyObject *v,
14293 struct unicode_format_arg_t *arg,
14294 PyObject **p_output,
14295 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014296{
14297 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014298 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014299
14300 if (!PyNumber_Check(v))
14301 goto wrongtype;
14302
Ethan Furman9ab74802014-03-21 06:38:46 -070014303 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014304 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014305 if (type == 'o' || type == 'x' || type == 'X') {
14306 iobj = PyNumber_Index(v);
14307 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014308 if (PyErr_ExceptionMatches(PyExc_TypeError))
14309 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014310 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014311 }
14312 }
14313 else {
14314 iobj = PyNumber_Long(v);
14315 if (iobj == NULL ) {
14316 if (PyErr_ExceptionMatches(PyExc_TypeError))
14317 goto wrongtype;
14318 return -1;
14319 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014320 }
14321 assert(PyLong_Check(iobj));
14322 }
14323 else {
14324 iobj = v;
14325 Py_INCREF(iobj);
14326 }
14327
14328 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014329 && arg->width == -1 && arg->prec == -1
14330 && !(arg->flags & (F_SIGN | F_BLANK))
14331 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014332 {
14333 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014334 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014335 int base;
14336
Victor Stinnera47082312012-10-04 02:19:54 +020014337 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014338 {
14339 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014340 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014341 case 'd':
14342 case 'i':
14343 case 'u':
14344 base = 10;
14345 break;
14346 case 'o':
14347 base = 8;
14348 break;
14349 case 'x':
14350 case 'X':
14351 base = 16;
14352 break;
14353 }
14354
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014355 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14356 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014357 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014358 }
14359 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014360 return 1;
14361 }
14362
Ethan Furmanb95b5612015-01-23 20:05:18 -080014363 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014364 Py_DECREF(iobj);
14365 if (res == NULL)
14366 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014367 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014368 return 0;
14369
14370wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014371 switch(type)
14372 {
14373 case 'o':
14374 case 'x':
14375 case 'X':
14376 PyErr_Format(PyExc_TypeError,
14377 "%%%c format: an integer is required, "
14378 "not %.200s",
14379 type, Py_TYPE(v)->tp_name);
14380 break;
14381 default:
14382 PyErr_Format(PyExc_TypeError,
14383 "%%%c format: a number is required, "
14384 "not %.200s",
14385 type, Py_TYPE(v)->tp_name);
14386 break;
14387 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014388 return -1;
14389}
14390
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014391static Py_UCS4
14392formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014393{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014394 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014395 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014396 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014397 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014398 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014399 goto onError;
14400 }
14401 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014402 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014403 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014404 /* make sure number is a type of integer */
14405 if (!PyLong_Check(v)) {
14406 iobj = PyNumber_Index(v);
14407 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014408 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014409 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014410 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014411 Py_DECREF(iobj);
14412 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014413 else {
14414 x = PyLong_AsLong(v);
14415 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014416 if (x == -1 && PyErr_Occurred())
14417 goto onError;
14418
Victor Stinner8faf8212011-12-08 22:14:11 +010014419 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014420 PyErr_SetString(PyExc_OverflowError,
14421 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014422 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014423 }
14424
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014425 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014426 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014427
Benjamin Peterson29060642009-01-31 22:14:21 +000014428 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014429 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014430 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014431 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014432}
14433
Victor Stinnera47082312012-10-04 02:19:54 +020014434/* Parse options of an argument: flags, width, precision.
14435 Handle also "%(name)" syntax.
14436
14437 Return 0 if the argument has been formatted into arg->str.
14438 Return 1 if the argument has been written into ctx->writer,
14439 Raise an exception and return -1 on error. */
14440static int
14441unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14442 struct unicode_format_arg_t *arg)
14443{
14444#define FORMAT_READ(ctx) \
14445 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14446
14447 PyObject *v;
14448
Victor Stinnera47082312012-10-04 02:19:54 +020014449 if (arg->ch == '(') {
14450 /* Get argument value from a dictionary. Example: "%(name)s". */
14451 Py_ssize_t keystart;
14452 Py_ssize_t keylen;
14453 PyObject *key;
14454 int pcount = 1;
14455
14456 if (ctx->dict == NULL) {
14457 PyErr_SetString(PyExc_TypeError,
14458 "format requires a mapping");
14459 return -1;
14460 }
14461 ++ctx->fmtpos;
14462 --ctx->fmtcnt;
14463 keystart = ctx->fmtpos;
14464 /* Skip over balanced parentheses */
14465 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14466 arg->ch = FORMAT_READ(ctx);
14467 if (arg->ch == ')')
14468 --pcount;
14469 else if (arg->ch == '(')
14470 ++pcount;
14471 ctx->fmtpos++;
14472 }
14473 keylen = ctx->fmtpos - keystart - 1;
14474 if (ctx->fmtcnt < 0 || pcount > 0) {
14475 PyErr_SetString(PyExc_ValueError,
14476 "incomplete format key");
14477 return -1;
14478 }
14479 key = PyUnicode_Substring(ctx->fmtstr,
14480 keystart, keystart + keylen);
14481 if (key == NULL)
14482 return -1;
14483 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014484 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014485 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014486 }
14487 ctx->args = PyObject_GetItem(ctx->dict, key);
14488 Py_DECREF(key);
14489 if (ctx->args == NULL)
14490 return -1;
14491 ctx->args_owned = 1;
14492 ctx->arglen = -1;
14493 ctx->argidx = -2;
14494 }
14495
14496 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014497 while (--ctx->fmtcnt >= 0) {
14498 arg->ch = FORMAT_READ(ctx);
14499 ctx->fmtpos++;
14500 switch (arg->ch) {
14501 case '-': arg->flags |= F_LJUST; continue;
14502 case '+': arg->flags |= F_SIGN; continue;
14503 case ' ': arg->flags |= F_BLANK; continue;
14504 case '#': arg->flags |= F_ALT; continue;
14505 case '0': arg->flags |= F_ZERO; continue;
14506 }
14507 break;
14508 }
14509
14510 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014511 if (arg->ch == '*') {
14512 v = unicode_format_getnextarg(ctx);
14513 if (v == NULL)
14514 return -1;
14515 if (!PyLong_Check(v)) {
14516 PyErr_SetString(PyExc_TypeError,
14517 "* wants int");
14518 return -1;
14519 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014520 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014521 if (arg->width == -1 && PyErr_Occurred())
14522 return -1;
14523 if (arg->width < 0) {
14524 arg->flags |= F_LJUST;
14525 arg->width = -arg->width;
14526 }
14527 if (--ctx->fmtcnt >= 0) {
14528 arg->ch = FORMAT_READ(ctx);
14529 ctx->fmtpos++;
14530 }
14531 }
14532 else if (arg->ch >= '0' && arg->ch <= '9') {
14533 arg->width = arg->ch - '0';
14534 while (--ctx->fmtcnt >= 0) {
14535 arg->ch = FORMAT_READ(ctx);
14536 ctx->fmtpos++;
14537 if (arg->ch < '0' || arg->ch > '9')
14538 break;
14539 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14540 mixing signed and unsigned comparison. Since arg->ch is between
14541 '0' and '9', casting to int is safe. */
14542 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14543 PyErr_SetString(PyExc_ValueError,
14544 "width too big");
14545 return -1;
14546 }
14547 arg->width = arg->width*10 + (arg->ch - '0');
14548 }
14549 }
14550
14551 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014552 if (arg->ch == '.') {
14553 arg->prec = 0;
14554 if (--ctx->fmtcnt >= 0) {
14555 arg->ch = FORMAT_READ(ctx);
14556 ctx->fmtpos++;
14557 }
14558 if (arg->ch == '*') {
14559 v = unicode_format_getnextarg(ctx);
14560 if (v == NULL)
14561 return -1;
14562 if (!PyLong_Check(v)) {
14563 PyErr_SetString(PyExc_TypeError,
14564 "* wants int");
14565 return -1;
14566 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014567 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014568 if (arg->prec == -1 && PyErr_Occurred())
14569 return -1;
14570 if (arg->prec < 0)
14571 arg->prec = 0;
14572 if (--ctx->fmtcnt >= 0) {
14573 arg->ch = FORMAT_READ(ctx);
14574 ctx->fmtpos++;
14575 }
14576 }
14577 else if (arg->ch >= '0' && arg->ch <= '9') {
14578 arg->prec = arg->ch - '0';
14579 while (--ctx->fmtcnt >= 0) {
14580 arg->ch = FORMAT_READ(ctx);
14581 ctx->fmtpos++;
14582 if (arg->ch < '0' || arg->ch > '9')
14583 break;
14584 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14585 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014586 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014587 return -1;
14588 }
14589 arg->prec = arg->prec*10 + (arg->ch - '0');
14590 }
14591 }
14592 }
14593
14594 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14595 if (ctx->fmtcnt >= 0) {
14596 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14597 if (--ctx->fmtcnt >= 0) {
14598 arg->ch = FORMAT_READ(ctx);
14599 ctx->fmtpos++;
14600 }
14601 }
14602 }
14603 if (ctx->fmtcnt < 0) {
14604 PyErr_SetString(PyExc_ValueError,
14605 "incomplete format");
14606 return -1;
14607 }
14608 return 0;
14609
14610#undef FORMAT_READ
14611}
14612
14613/* Format one argument. Supported conversion specifiers:
14614
14615 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014616 - "i", "d", "u": int or float
14617 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014618 - "e", "E", "f", "F", "g", "G": float
14619 - "c": int or str (1 character)
14620
Victor Stinner8dbd4212012-12-04 09:30:24 +010014621 When possible, the output is written directly into the Unicode writer
14622 (ctx->writer). A string is created when padding is required.
14623
Victor Stinnera47082312012-10-04 02:19:54 +020014624 Return 0 if the argument has been formatted into *p_str,
14625 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014626 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014627static int
14628unicode_format_arg_format(struct unicode_formatter_t *ctx,
14629 struct unicode_format_arg_t *arg,
14630 PyObject **p_str)
14631{
14632 PyObject *v;
14633 _PyUnicodeWriter *writer = &ctx->writer;
14634
14635 if (ctx->fmtcnt == 0)
14636 ctx->writer.overallocate = 0;
14637
Victor Stinnera47082312012-10-04 02:19:54 +020014638 v = unicode_format_getnextarg(ctx);
14639 if (v == NULL)
14640 return -1;
14641
Victor Stinnera47082312012-10-04 02:19:54 +020014642
14643 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014644 case 's':
14645 case 'r':
14646 case 'a':
14647 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14648 /* Fast path */
14649 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14650 return -1;
14651 return 1;
14652 }
14653
14654 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14655 *p_str = v;
14656 Py_INCREF(*p_str);
14657 }
14658 else {
14659 if (arg->ch == 's')
14660 *p_str = PyObject_Str(v);
14661 else if (arg->ch == 'r')
14662 *p_str = PyObject_Repr(v);
14663 else
14664 *p_str = PyObject_ASCII(v);
14665 }
14666 break;
14667
14668 case 'i':
14669 case 'd':
14670 case 'u':
14671 case 'o':
14672 case 'x':
14673 case 'X':
14674 {
14675 int ret = mainformatlong(v, arg, p_str, writer);
14676 if (ret != 0)
14677 return ret;
14678 arg->sign = 1;
14679 break;
14680 }
14681
14682 case 'e':
14683 case 'E':
14684 case 'f':
14685 case 'F':
14686 case 'g':
14687 case 'G':
14688 if (arg->width == -1 && arg->prec == -1
14689 && !(arg->flags & (F_SIGN | F_BLANK)))
14690 {
14691 /* Fast path */
14692 if (formatfloat(v, arg, NULL, writer) == -1)
14693 return -1;
14694 return 1;
14695 }
14696
14697 arg->sign = 1;
14698 if (formatfloat(v, arg, p_str, NULL) == -1)
14699 return -1;
14700 break;
14701
14702 case 'c':
14703 {
14704 Py_UCS4 ch = formatchar(v);
14705 if (ch == (Py_UCS4) -1)
14706 return -1;
14707 if (arg->width == -1 && arg->prec == -1) {
14708 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014709 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014710 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014711 return 1;
14712 }
14713 *p_str = PyUnicode_FromOrdinal(ch);
14714 break;
14715 }
14716
14717 default:
14718 PyErr_Format(PyExc_ValueError,
14719 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014720 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014721 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14722 (int)arg->ch,
14723 ctx->fmtpos - 1);
14724 return -1;
14725 }
14726 if (*p_str == NULL)
14727 return -1;
14728 assert (PyUnicode_Check(*p_str));
14729 return 0;
14730}
14731
14732static int
14733unicode_format_arg_output(struct unicode_formatter_t *ctx,
14734 struct unicode_format_arg_t *arg,
14735 PyObject *str)
14736{
14737 Py_ssize_t len;
14738 enum PyUnicode_Kind kind;
14739 void *pbuf;
14740 Py_ssize_t pindex;
14741 Py_UCS4 signchar;
14742 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014743 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014744 Py_ssize_t sublen;
14745 _PyUnicodeWriter *writer = &ctx->writer;
14746 Py_UCS4 fill;
14747
14748 fill = ' ';
14749 if (arg->sign && arg->flags & F_ZERO)
14750 fill = '0';
14751
14752 if (PyUnicode_READY(str) == -1)
14753 return -1;
14754
14755 len = PyUnicode_GET_LENGTH(str);
14756 if ((arg->width == -1 || arg->width <= len)
14757 && (arg->prec == -1 || arg->prec >= len)
14758 && !(arg->flags & (F_SIGN | F_BLANK)))
14759 {
14760 /* Fast path */
14761 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14762 return -1;
14763 return 0;
14764 }
14765
14766 /* Truncate the string for "s", "r" and "a" formats
14767 if the precision is set */
14768 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14769 if (arg->prec >= 0 && len > arg->prec)
14770 len = arg->prec;
14771 }
14772
14773 /* Adjust sign and width */
14774 kind = PyUnicode_KIND(str);
14775 pbuf = PyUnicode_DATA(str);
14776 pindex = 0;
14777 signchar = '\0';
14778 if (arg->sign) {
14779 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14780 if (ch == '-' || ch == '+') {
14781 signchar = ch;
14782 len--;
14783 pindex++;
14784 }
14785 else if (arg->flags & F_SIGN)
14786 signchar = '+';
14787 else if (arg->flags & F_BLANK)
14788 signchar = ' ';
14789 else
14790 arg->sign = 0;
14791 }
14792 if (arg->width < len)
14793 arg->width = len;
14794
14795 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014796 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014797 if (!(arg->flags & F_LJUST)) {
14798 if (arg->sign) {
14799 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014800 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014801 }
14802 else {
14803 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014804 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014805 }
14806 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014807 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14808 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014809 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014810 }
14811
Victor Stinnera47082312012-10-04 02:19:54 +020014812 buflen = arg->width;
14813 if (arg->sign && len == arg->width)
14814 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014815 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014816 return -1;
14817
14818 /* Write the sign if needed */
14819 if (arg->sign) {
14820 if (fill != ' ') {
14821 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14822 writer->pos += 1;
14823 }
14824 if (arg->width > len)
14825 arg->width--;
14826 }
14827
14828 /* Write the numeric prefix for "x", "X" and "o" formats
14829 if the alternate form is used.
14830 For example, write "0x" for the "%#x" format. */
14831 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14832 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14833 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14834 if (fill != ' ') {
14835 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14836 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14837 writer->pos += 2;
14838 pindex += 2;
14839 }
14840 arg->width -= 2;
14841 if (arg->width < 0)
14842 arg->width = 0;
14843 len -= 2;
14844 }
14845
14846 /* Pad left with the fill character if needed */
14847 if (arg->width > len && !(arg->flags & F_LJUST)) {
14848 sublen = arg->width - len;
14849 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14850 writer->pos += sublen;
14851 arg->width = len;
14852 }
14853
14854 /* If padding with spaces: write sign if needed and/or numeric prefix if
14855 the alternate form is used */
14856 if (fill == ' ') {
14857 if (arg->sign) {
14858 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14859 writer->pos += 1;
14860 }
14861 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14862 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14863 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14864 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14865 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14866 writer->pos += 2;
14867 pindex += 2;
14868 }
14869 }
14870
14871 /* Write characters */
14872 if (len) {
14873 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14874 str, pindex, len);
14875 writer->pos += len;
14876 }
14877
14878 /* Pad right with the fill character if needed */
14879 if (arg->width > len) {
14880 sublen = arg->width - len;
14881 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14882 writer->pos += sublen;
14883 }
14884 return 0;
14885}
14886
14887/* Helper of PyUnicode_Format(): format one arg.
14888 Return 0 on success, raise an exception and return -1 on error. */
14889static int
14890unicode_format_arg(struct unicode_formatter_t *ctx)
14891{
14892 struct unicode_format_arg_t arg;
14893 PyObject *str;
14894 int ret;
14895
Victor Stinner8dbd4212012-12-04 09:30:24 +010014896 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014897 if (arg.ch == '%') {
14898 ctx->fmtpos++;
14899 ctx->fmtcnt--;
14900 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14901 return -1;
14902 return 0;
14903 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014904 arg.flags = 0;
14905 arg.width = -1;
14906 arg.prec = -1;
14907 arg.sign = 0;
14908 str = NULL;
14909
Victor Stinnera47082312012-10-04 02:19:54 +020014910 ret = unicode_format_arg_parse(ctx, &arg);
14911 if (ret == -1)
14912 return -1;
14913
14914 ret = unicode_format_arg_format(ctx, &arg, &str);
14915 if (ret == -1)
14916 return -1;
14917
14918 if (ret != 1) {
14919 ret = unicode_format_arg_output(ctx, &arg, str);
14920 Py_DECREF(str);
14921 if (ret == -1)
14922 return -1;
14923 }
14924
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014925 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014926 PyErr_SetString(PyExc_TypeError,
14927 "not all arguments converted during string formatting");
14928 return -1;
14929 }
14930 return 0;
14931}
14932
Alexander Belopolsky40018472011-02-26 01:02:56 +000014933PyObject *
14934PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014935{
Victor Stinnera47082312012-10-04 02:19:54 +020014936 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014937
Guido van Rossumd57fd912000-03-10 22:53:23 +000014938 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014939 PyErr_BadInternalCall();
14940 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014941 }
Victor Stinnera47082312012-10-04 02:19:54 +020014942
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014943 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014944 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014945
14946 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014947 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14948 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14949 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14950 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014951
Victor Stinner8f674cc2013-04-17 23:02:17 +020014952 _PyUnicodeWriter_Init(&ctx.writer);
14953 ctx.writer.min_length = ctx.fmtcnt + 100;
14954 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014955
Guido van Rossumd57fd912000-03-10 22:53:23 +000014956 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014957 ctx.arglen = PyTuple_Size(args);
14958 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014959 }
14960 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014961 ctx.arglen = -1;
14962 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014963 }
Victor Stinnera47082312012-10-04 02:19:54 +020014964 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014965 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014966 ctx.dict = args;
14967 else
14968 ctx.dict = NULL;
14969 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014970
Victor Stinnera47082312012-10-04 02:19:54 +020014971 while (--ctx.fmtcnt >= 0) {
14972 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014973 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014974
14975 nonfmtpos = ctx.fmtpos++;
14976 while (ctx.fmtcnt >= 0 &&
14977 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14978 ctx.fmtpos++;
14979 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014980 }
Victor Stinnera47082312012-10-04 02:19:54 +020014981 if (ctx.fmtcnt < 0) {
14982 ctx.fmtpos--;
14983 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014984 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014985
Victor Stinnercfc4c132013-04-03 01:48:39 +020014986 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14987 nonfmtpos, ctx.fmtpos) < 0)
14988 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014989 }
14990 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014991 ctx.fmtpos++;
14992 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014993 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014994 }
14995 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014996
Victor Stinnera47082312012-10-04 02:19:54 +020014997 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014998 PyErr_SetString(PyExc_TypeError,
14999 "not all arguments converted during string formatting");
15000 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015001 }
15002
Victor Stinnera47082312012-10-04 02:19:54 +020015003 if (ctx.args_owned) {
15004 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015005 }
Victor Stinnera47082312012-10-04 02:19:54 +020015006 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015007
Benjamin Peterson29060642009-01-31 22:14:21 +000015008 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015009 _PyUnicodeWriter_Dealloc(&ctx.writer);
15010 if (ctx.args_owned) {
15011 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015012 }
15013 return NULL;
15014}
15015
Jeremy Hylton938ace62002-07-17 16:30:39 +000015016static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015017unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15018
Tim Peters6d6c1a32001-08-02 04:15:00 +000015019static PyObject *
15020unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15021{
Benjamin Peterson29060642009-01-31 22:14:21 +000015022 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015023 static char *kwlist[] = {"object", "encoding", "errors", 0};
15024 char *encoding = NULL;
15025 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015026
Benjamin Peterson14339b62009-01-31 16:36:08 +000015027 if (type != &PyUnicode_Type)
15028 return unicode_subtype_new(type, args, kwds);
15029 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015030 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015031 return NULL;
15032 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015033 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015034 if (encoding == NULL && errors == NULL)
15035 return PyObject_Str(x);
15036 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015037 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015038}
15039
Guido van Rossume023fe02001-08-30 03:12:59 +000015040static PyObject *
15041unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15042{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015043 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044 Py_ssize_t length, char_size;
15045 int share_wstr, share_utf8;
15046 unsigned int kind;
15047 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015048
Benjamin Peterson14339b62009-01-31 16:36:08 +000015049 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015050
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015051 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015052 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015053 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015054 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015055 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015056 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015057 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015058 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015059
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015060 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015061 if (self == NULL) {
15062 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015063 return NULL;
15064 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015065 kind = PyUnicode_KIND(unicode);
15066 length = PyUnicode_GET_LENGTH(unicode);
15067
15068 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015069#ifdef Py_DEBUG
15070 _PyUnicode_HASH(self) = -1;
15071#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015072 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015073#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015074 _PyUnicode_STATE(self).interned = 0;
15075 _PyUnicode_STATE(self).kind = kind;
15076 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015077 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015078 _PyUnicode_STATE(self).ready = 1;
15079 _PyUnicode_WSTR(self) = NULL;
15080 _PyUnicode_UTF8_LENGTH(self) = 0;
15081 _PyUnicode_UTF8(self) = NULL;
15082 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015083 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015084
15085 share_utf8 = 0;
15086 share_wstr = 0;
15087 if (kind == PyUnicode_1BYTE_KIND) {
15088 char_size = 1;
15089 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15090 share_utf8 = 1;
15091 }
15092 else if (kind == PyUnicode_2BYTE_KIND) {
15093 char_size = 2;
15094 if (sizeof(wchar_t) == 2)
15095 share_wstr = 1;
15096 }
15097 else {
15098 assert(kind == PyUnicode_4BYTE_KIND);
15099 char_size = 4;
15100 if (sizeof(wchar_t) == 4)
15101 share_wstr = 1;
15102 }
15103
15104 /* Ensure we won't overflow the length. */
15105 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15106 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015107 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015108 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015109 data = PyObject_MALLOC((length + 1) * char_size);
15110 if (data == NULL) {
15111 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015112 goto onError;
15113 }
15114
Victor Stinnerc3c74152011-10-02 20:39:55 +020015115 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015116 if (share_utf8) {
15117 _PyUnicode_UTF8_LENGTH(self) = length;
15118 _PyUnicode_UTF8(self) = data;
15119 }
15120 if (share_wstr) {
15121 _PyUnicode_WSTR_LENGTH(self) = length;
15122 _PyUnicode_WSTR(self) = (wchar_t *)data;
15123 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015124
Christian Heimesf051e432016-09-13 20:22:02 +020015125 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015126 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015127 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015128#ifdef Py_DEBUG
15129 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15130#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015131 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015132 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015133
15134onError:
15135 Py_DECREF(unicode);
15136 Py_DECREF(self);
15137 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015138}
15139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015140PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015141"str(object='') -> str\n\
15142str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015143\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015144Create a new string object from the given object. If encoding or\n\
15145errors is specified, then the object must expose a data buffer\n\
15146that will be decoded using the given encoding and error handler.\n\
15147Otherwise, returns the result of object.__str__() (if defined)\n\
15148or repr(object).\n\
15149encoding defaults to sys.getdefaultencoding().\n\
15150errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015151
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015152static PyObject *unicode_iter(PyObject *seq);
15153
Guido van Rossumd57fd912000-03-10 22:53:23 +000015154PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015155 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015156 "str", /* tp_name */
15157 sizeof(PyUnicodeObject), /* tp_size */
15158 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015159 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015160 (destructor)unicode_dealloc, /* tp_dealloc */
15161 0, /* tp_print */
15162 0, /* tp_getattr */
15163 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015164 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015165 unicode_repr, /* tp_repr */
15166 &unicode_as_number, /* tp_as_number */
15167 &unicode_as_sequence, /* tp_as_sequence */
15168 &unicode_as_mapping, /* tp_as_mapping */
15169 (hashfunc) unicode_hash, /* tp_hash*/
15170 0, /* tp_call*/
15171 (reprfunc) unicode_str, /* tp_str */
15172 PyObject_GenericGetAttr, /* tp_getattro */
15173 0, /* tp_setattro */
15174 0, /* tp_as_buffer */
15175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015176 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 unicode_doc, /* tp_doc */
15178 0, /* tp_traverse */
15179 0, /* tp_clear */
15180 PyUnicode_RichCompare, /* tp_richcompare */
15181 0, /* tp_weaklistoffset */
15182 unicode_iter, /* tp_iter */
15183 0, /* tp_iternext */
15184 unicode_methods, /* tp_methods */
15185 0, /* tp_members */
15186 0, /* tp_getset */
15187 &PyBaseObject_Type, /* tp_base */
15188 0, /* tp_dict */
15189 0, /* tp_descr_get */
15190 0, /* tp_descr_set */
15191 0, /* tp_dictoffset */
15192 0, /* tp_init */
15193 0, /* tp_alloc */
15194 unicode_new, /* tp_new */
15195 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015196};
15197
15198/* Initialize the Unicode implementation */
15199
Victor Stinner3a50e702011-10-18 21:21:00 +020015200int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015201{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015202 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015203 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015204 0x000A, /* LINE FEED */
15205 0x000D, /* CARRIAGE RETURN */
15206 0x001C, /* FILE SEPARATOR */
15207 0x001D, /* GROUP SEPARATOR */
15208 0x001E, /* RECORD SEPARATOR */
15209 0x0085, /* NEXT LINE */
15210 0x2028, /* LINE SEPARATOR */
15211 0x2029, /* PARAGRAPH SEPARATOR */
15212 };
15213
Fred Drakee4315f52000-05-09 19:53:39 +000015214 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015215 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015216 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015217 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015218 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015219
Guido van Rossumcacfc072002-05-24 19:01:59 +000015220 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015221 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015222
15223 /* initialize the linebreak bloom filter */
15224 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015225 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015226 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015227
Christian Heimes26532f72013-07-20 14:57:16 +020015228 if (PyType_Ready(&EncodingMapType) < 0)
15229 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015230
Benjamin Petersonc4311282012-10-30 23:21:10 -040015231 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15232 Py_FatalError("Can't initialize field name iterator type");
15233
15234 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15235 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015236
Victor Stinner3a50e702011-10-18 21:21:00 +020015237 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015238}
15239
15240/* Finalize the Unicode implementation */
15241
Christian Heimesa156e092008-02-16 07:38:31 +000015242int
15243PyUnicode_ClearFreeList(void)
15244{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015245 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015246}
15247
Guido van Rossumd57fd912000-03-10 22:53:23 +000015248void
Thomas Wouters78890102000-07-22 19:25:51 +000015249_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015250{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015251 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015252
Serhiy Storchaka05997252013-01-26 12:14:02 +020015253 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015254
Serhiy Storchaka05997252013-01-26 12:14:02 +020015255 for (i = 0; i < 256; i++)
15256 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015257 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015258 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015259}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015260
Walter Dörwald16807132007-05-25 13:52:07 +000015261void
15262PyUnicode_InternInPlace(PyObject **p)
15263{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015264 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015266#ifdef Py_DEBUG
15267 assert(s != NULL);
15268 assert(_PyUnicode_CHECK(s));
15269#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015270 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015271 return;
15272#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 /* If it's a subclass, we don't really know what putting
15274 it in the interned dict might do. */
15275 if (!PyUnicode_CheckExact(s))
15276 return;
15277 if (PyUnicode_CHECK_INTERNED(s))
15278 return;
15279 if (interned == NULL) {
15280 interned = PyDict_New();
15281 if (interned == NULL) {
15282 PyErr_Clear(); /* Don't leave an exception */
15283 return;
15284 }
15285 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015287 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015288 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015289 if (t == NULL) {
15290 PyErr_Clear();
15291 return;
15292 }
15293 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015294 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015295 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015296 return;
15297 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015298 /* The two references in interned are not counted by refcnt.
15299 The deallocator will take care of this */
15300 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015301 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015302}
15303
15304void
15305PyUnicode_InternImmortal(PyObject **p)
15306{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015307 PyUnicode_InternInPlace(p);
15308 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015309 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015310 Py_INCREF(*p);
15311 }
Walter Dörwald16807132007-05-25 13:52:07 +000015312}
15313
15314PyObject *
15315PyUnicode_InternFromString(const char *cp)
15316{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015317 PyObject *s = PyUnicode_FromString(cp);
15318 if (s == NULL)
15319 return NULL;
15320 PyUnicode_InternInPlace(&s);
15321 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015322}
15323
Alexander Belopolsky40018472011-02-26 01:02:56 +000015324void
15325_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015326{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015327 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015328 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015329 Py_ssize_t i, n;
15330 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015331
Benjamin Peterson14339b62009-01-31 16:36:08 +000015332 if (interned == NULL || !PyDict_Check(interned))
15333 return;
15334 keys = PyDict_Keys(interned);
15335 if (keys == NULL || !PyList_Check(keys)) {
15336 PyErr_Clear();
15337 return;
15338 }
Walter Dörwald16807132007-05-25 13:52:07 +000015339
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15341 detector, interned unicode strings are not forcibly deallocated;
15342 rather, we give them their stolen references back, and then clear
15343 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015344
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 n = PyList_GET_SIZE(keys);
15346 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015347 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015348 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015349 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015350 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015351 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015352 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015353 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015354 case SSTATE_NOT_INTERNED:
15355 /* XXX Shouldn't happen */
15356 break;
15357 case SSTATE_INTERNED_IMMORTAL:
15358 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015359 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015360 break;
15361 case SSTATE_INTERNED_MORTAL:
15362 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015363 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015364 break;
15365 default:
15366 Py_FatalError("Inconsistent interned string state.");
15367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015368 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015369 }
15370 fprintf(stderr, "total size of all interned strings: "
15371 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15372 "mortal/immortal\n", mortal_size, immortal_size);
15373 Py_DECREF(keys);
15374 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015375 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015376}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015377
15378
15379/********************* Unicode Iterator **************************/
15380
15381typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 PyObject_HEAD
15383 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015384 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015385} unicodeiterobject;
15386
15387static void
15388unicodeiter_dealloc(unicodeiterobject *it)
15389{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015390 _PyObject_GC_UNTRACK(it);
15391 Py_XDECREF(it->it_seq);
15392 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015393}
15394
15395static int
15396unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15397{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015398 Py_VISIT(it->it_seq);
15399 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015400}
15401
15402static PyObject *
15403unicodeiter_next(unicodeiterobject *it)
15404{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015405 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015406
Benjamin Peterson14339b62009-01-31 16:36:08 +000015407 assert(it != NULL);
15408 seq = it->it_seq;
15409 if (seq == NULL)
15410 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015411 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015413 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15414 int kind = PyUnicode_KIND(seq);
15415 void *data = PyUnicode_DATA(seq);
15416 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15417 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015418 if (item != NULL)
15419 ++it->it_index;
15420 return item;
15421 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015422
Benjamin Peterson14339b62009-01-31 16:36:08 +000015423 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015424 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015425 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015426}
15427
15428static PyObject *
15429unicodeiter_len(unicodeiterobject *it)
15430{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015431 Py_ssize_t len = 0;
15432 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015433 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015434 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015435}
15436
15437PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15438
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015439static PyObject *
15440unicodeiter_reduce(unicodeiterobject *it)
15441{
15442 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015443 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015444 it->it_seq, it->it_index);
15445 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015446 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015447 if (u == NULL)
15448 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015449 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015450 }
15451}
15452
15453PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15454
15455static PyObject *
15456unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15457{
15458 Py_ssize_t index = PyLong_AsSsize_t(state);
15459 if (index == -1 && PyErr_Occurred())
15460 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015461 if (it->it_seq != NULL) {
15462 if (index < 0)
15463 index = 0;
15464 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15465 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15466 it->it_index = index;
15467 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015468 Py_RETURN_NONE;
15469}
15470
15471PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15472
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015473static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015474 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015475 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015476 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15477 reduce_doc},
15478 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15479 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015480 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015481};
15482
15483PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015484 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15485 "str_iterator", /* tp_name */
15486 sizeof(unicodeiterobject), /* tp_basicsize */
15487 0, /* tp_itemsize */
15488 /* methods */
15489 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15490 0, /* tp_print */
15491 0, /* tp_getattr */
15492 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015493 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015494 0, /* tp_repr */
15495 0, /* tp_as_number */
15496 0, /* tp_as_sequence */
15497 0, /* tp_as_mapping */
15498 0, /* tp_hash */
15499 0, /* tp_call */
15500 0, /* tp_str */
15501 PyObject_GenericGetAttr, /* tp_getattro */
15502 0, /* tp_setattro */
15503 0, /* tp_as_buffer */
15504 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15505 0, /* tp_doc */
15506 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15507 0, /* tp_clear */
15508 0, /* tp_richcompare */
15509 0, /* tp_weaklistoffset */
15510 PyObject_SelfIter, /* tp_iter */
15511 (iternextfunc)unicodeiter_next, /* tp_iternext */
15512 unicodeiter_methods, /* tp_methods */
15513 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015514};
15515
15516static PyObject *
15517unicode_iter(PyObject *seq)
15518{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015519 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015520
Benjamin Peterson14339b62009-01-31 16:36:08 +000015521 if (!PyUnicode_Check(seq)) {
15522 PyErr_BadInternalCall();
15523 return NULL;
15524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015525 if (PyUnicode_READY(seq) == -1)
15526 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015527 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15528 if (it == NULL)
15529 return NULL;
15530 it->it_index = 0;
15531 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015532 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015533 _PyObject_GC_TRACK(it);
15534 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015535}
15536
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015537
15538size_t
15539Py_UNICODE_strlen(const Py_UNICODE *u)
15540{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015541 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015542}
15543
15544Py_UNICODE*
15545Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15546{
15547 Py_UNICODE *u = s1;
15548 while ((*u++ = *s2++));
15549 return s1;
15550}
15551
15552Py_UNICODE*
15553Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15554{
15555 Py_UNICODE *u = s1;
15556 while ((*u++ = *s2++))
15557 if (n-- == 0)
15558 break;
15559 return s1;
15560}
15561
15562Py_UNICODE*
15563Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15564{
15565 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015566 u1 += wcslen(u1);
15567 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015568 return s1;
15569}
15570
15571int
15572Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15573{
15574 while (*s1 && *s2 && *s1 == *s2)
15575 s1++, s2++;
15576 if (*s1 && *s2)
15577 return (*s1 < *s2) ? -1 : +1;
15578 if (*s1)
15579 return 1;
15580 if (*s2)
15581 return -1;
15582 return 0;
15583}
15584
15585int
15586Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15587{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015588 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015589 for (; n != 0; n--) {
15590 u1 = *s1;
15591 u2 = *s2;
15592 if (u1 != u2)
15593 return (u1 < u2) ? -1 : +1;
15594 if (u1 == '\0')
15595 return 0;
15596 s1++;
15597 s2++;
15598 }
15599 return 0;
15600}
15601
15602Py_UNICODE*
15603Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15604{
15605 const Py_UNICODE *p;
15606 for (p = s; *p; p++)
15607 if (*p == c)
15608 return (Py_UNICODE*)p;
15609 return NULL;
15610}
15611
15612Py_UNICODE*
15613Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15614{
15615 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015616 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015617 while (p != s) {
15618 p--;
15619 if (*p == c)
15620 return (Py_UNICODE*)p;
15621 }
15622 return NULL;
15623}
Victor Stinner331ea922010-08-10 16:37:20 +000015624
Victor Stinner71133ff2010-09-01 23:43:53 +000015625Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015626PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015627{
Victor Stinner577db2c2011-10-11 22:12:48 +020015628 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015629 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015631 if (!PyUnicode_Check(unicode)) {
15632 PyErr_BadArgument();
15633 return NULL;
15634 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015635 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015636 if (u == NULL)
15637 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015638 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015639 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015640 PyErr_NoMemory();
15641 return NULL;
15642 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015643 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015644 size *= sizeof(Py_UNICODE);
15645 copy = PyMem_Malloc(size);
15646 if (copy == NULL) {
15647 PyErr_NoMemory();
15648 return NULL;
15649 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015650 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015651 return copy;
15652}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015653
Georg Brandl66c221e2010-10-14 07:04:07 +000015654/* A _string module, to export formatter_parser and formatter_field_name_split
15655 to the string.Formatter class implemented in Python. */
15656
15657static PyMethodDef _string_methods[] = {
15658 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15659 METH_O, PyDoc_STR("split the argument as a field name")},
15660 {"formatter_parser", (PyCFunction) formatter_parser,
15661 METH_O, PyDoc_STR("parse the argument as a format string")},
15662 {NULL, NULL}
15663};
15664
15665static struct PyModuleDef _string_module = {
15666 PyModuleDef_HEAD_INIT,
15667 "_string",
15668 PyDoc_STR("string helper module"),
15669 0,
15670 _string_methods,
15671 NULL,
15672 NULL,
15673 NULL,
15674 NULL
15675};
15676
15677PyMODINIT_FUNC
15678PyInit__string(void)
15679{
15680 return PyModule_Create(&_string_module);
15681}
15682
15683
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015684#ifdef __cplusplus
15685}
15686#endif