blob: e18937981bb763d508aa7aa8811bda6f89df8c67 [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 Stinner6f5fa1b2018-11-26 14:17:01 +0100221#define FILL(kind, data, value, start, length) \
222 do { \
Victor Stinner7f9fb0f2018-11-27 12:42:04 +0100223 assert(0 <= start); \
Victor Stinner6f5fa1b2018-11-26 14:17:01 +0100224 assert(kind != PyUnicode_WCHAR_KIND); \
Victor Stinner7f9fb0f2018-11-27 12:42:04 +0100225 switch (kind) { \
Victor Stinner6f5fa1b2018-11-26 14:17:01 +0100226 case PyUnicode_1BYTE_KIND: { \
Victor Stinner7f9fb0f2018-11-27 12:42:04 +0100227 assert(value <= 0xff); \
228 Py_UCS1 ch = (unsigned char)value; \
229 Py_UCS1 *to = (Py_UCS1 *)data + start; \
230 memset(to, ch, length); \
Victor Stinner6f5fa1b2018-11-26 14:17:01 +0100231 break; \
232 } \
233 case PyUnicode_2BYTE_KIND: { \
Victor Stinner7f9fb0f2018-11-27 12:42:04 +0100234 assert(value <= 0xffff); \
235 Py_UCS2 ch = (Py_UCS2)value; \
236 Py_UCS2 *to = (Py_UCS2 *)data + start; \
237 const Py_UCS2 *end = to + length; \
238 for (; to < end; ++to) *to = ch; \
Victor Stinner6f5fa1b2018-11-26 14:17:01 +0100239 break; \
240 } \
241 case PyUnicode_4BYTE_KIND: { \
Victor Stinner7f9fb0f2018-11-27 12:42:04 +0100242 assert(value <= MAX_UNICODE); \
243 Py_UCS4 ch = value; \
244 Py_UCS4 * to = (Py_UCS4 *)data + start; \
245 const Py_UCS4 *end = to + length; \
246 for (; to < end; ++to) *to = ch; \
Victor Stinner6f5fa1b2018-11-26 14:17:01 +0100247 break; \
248 } \
249 default: Py_UNREACHABLE(); \
250 } \
251 } while (0)
252
253
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200254/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700255static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200256_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
257
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200258/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200259static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200260
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000261/* Single character Unicode strings in the Latin-1 range are being
262 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200263static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Fast detection of the most frequent whitespace characters */
266const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000270/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* case 0x000C: * FORM FEED */
272/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 1, 1, 1, 1, 1, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000275/* case 0x001C: * FILE SEPARATOR */
276/* case 0x001D: * GROUP SEPARATOR */
277/* case 0x001E: * RECORD SEPARATOR */
278/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000281 1, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000285
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000294};
295
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200296/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200297static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200298static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100299static int unicode_modifiable(PyObject *unicode);
300
Victor Stinnerfe226c02011-10-03 03:52:20 +0200301
Alexander Belopolsky40018472011-02-26 01:02:56 +0000302static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100303_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200304static PyObject *
305_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
306static PyObject *
307_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
308
309static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000310unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000311 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100312 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000313 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
314
Alexander Belopolsky40018472011-02-26 01:02:56 +0000315static void
316raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300317 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100318 PyObject *unicode,
319 Py_ssize_t startpos, Py_ssize_t endpos,
320 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000321
Christian Heimes190d79e2008-01-30 11:58:22 +0000322/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200323static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000324 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000325/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000326/* 0x000B, * LINE TABULATION */
327/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000328/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000329 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000330 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000331/* 0x001C, * FILE SEPARATOR */
332/* 0x001D, * GROUP SEPARATOR */
333/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000334 0, 0, 0, 0, 1, 1, 1, 0,
335 0, 0, 0, 0, 0, 0, 0, 0,
336 0, 0, 0, 0, 0, 0, 0, 0,
337 0, 0, 0, 0, 0, 0, 0, 0,
338 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000339
Benjamin Peterson14339b62009-01-31 16:36:08 +0000340 0, 0, 0, 0, 0, 0, 0, 0,
341 0, 0, 0, 0, 0, 0, 0, 0,
342 0, 0, 0, 0, 0, 0, 0, 0,
343 0, 0, 0, 0, 0, 0, 0, 0,
344 0, 0, 0, 0, 0, 0, 0, 0,
345 0, 0, 0, 0, 0, 0, 0, 0,
346 0, 0, 0, 0, 0, 0, 0, 0,
347 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000348};
349
INADA Naoki3ae20562017-01-16 20:41:20 +0900350static int convert_uc(PyObject *obj, void *addr);
351
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300352#include "clinic/unicodeobject.c.h"
353
Victor Stinner50149202015-09-22 00:26:54 +0200354typedef enum {
355 _Py_ERROR_UNKNOWN=0,
356 _Py_ERROR_STRICT,
357 _Py_ERROR_SURROGATEESCAPE,
358 _Py_ERROR_REPLACE,
359 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200360 _Py_ERROR_BACKSLASHREPLACE,
361 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200362 _Py_ERROR_XMLCHARREFREPLACE,
363 _Py_ERROR_OTHER
364} _Py_error_handler;
365
366static _Py_error_handler
367get_error_handler(const char *errors)
368{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200369 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200370 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200371 }
372 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200373 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200374 }
375 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200376 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200377 }
378 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200379 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200380 }
381 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200382 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200383 }
384 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200385 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200386 }
387 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200388 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200389 }
Victor Stinner50149202015-09-22 00:26:54 +0200390 return _Py_ERROR_OTHER;
391}
392
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300393/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
394 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000395Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000396PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000397{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000398#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000399 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000400#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000401 /* This is actually an illegal character, so it should
402 not be passed to unichr. */
403 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000404#endif
405}
406
Victor Stinner910337b2011-10-03 03:20:16 +0200407#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200408int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100409_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200410{
411 PyASCIIObject *ascii;
412 unsigned int kind;
413
414 assert(PyUnicode_Check(op));
415
416 ascii = (PyASCIIObject *)op;
417 kind = ascii->state.kind;
418
Victor Stinnera3b334d2011-10-03 13:53:37 +0200419 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200420 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200421 assert(ascii->state.ready == 1);
422 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200423 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200424 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200425 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200426
Victor Stinnera41463c2011-10-04 01:05:08 +0200427 if (ascii->state.compact == 1) {
428 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200429 assert(kind == PyUnicode_1BYTE_KIND
430 || kind == PyUnicode_2BYTE_KIND
431 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200432 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200433 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200434 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100435 }
436 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200437 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
438
439 data = unicode->data.any;
440 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100441 assert(ascii->length == 0);
442 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200443 assert(ascii->state.compact == 0);
444 assert(ascii->state.ascii == 0);
445 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100446 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200447 assert(ascii->wstr != NULL);
448 assert(data == NULL);
449 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200450 }
451 else {
452 assert(kind == PyUnicode_1BYTE_KIND
453 || kind == PyUnicode_2BYTE_KIND
454 || kind == PyUnicode_4BYTE_KIND);
455 assert(ascii->state.compact == 0);
456 assert(ascii->state.ready == 1);
457 assert(data != NULL);
458 if (ascii->state.ascii) {
459 assert (compact->utf8 == data);
460 assert (compact->utf8_length == ascii->length);
461 }
462 else
463 assert (compact->utf8 != data);
464 }
465 }
466 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200467 if (
468#if SIZEOF_WCHAR_T == 2
469 kind == PyUnicode_2BYTE_KIND
470#else
471 kind == PyUnicode_4BYTE_KIND
472#endif
473 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200474 {
475 assert(ascii->wstr == data);
476 assert(compact->wstr_length == ascii->length);
477 } else
478 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200479 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200480
481 if (compact->utf8 == NULL)
482 assert(compact->utf8_length == 0);
483 if (ascii->wstr == NULL)
484 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200485 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200486 /* check that the best kind is used */
487 if (check_content && kind != PyUnicode_WCHAR_KIND)
488 {
489 Py_ssize_t i;
490 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200491 void *data;
492 Py_UCS4 ch;
493
494 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200495 for (i=0; i < ascii->length; i++)
496 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200497 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200498 if (ch > maxchar)
499 maxchar = ch;
500 }
501 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100502 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200503 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100504 assert(maxchar <= 255);
505 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200506 else
507 assert(maxchar < 128);
508 }
Victor Stinner77faf692011-11-20 18:56:05 +0100509 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200510 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100511 assert(maxchar <= 0xFFFF);
512 }
513 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200514 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100515 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100516 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200517 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200518 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400519 return 1;
520}
Victor Stinner910337b2011-10-03 03:20:16 +0200521#endif
522
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100523static PyObject*
524unicode_result_wchar(PyObject *unicode)
525{
526#ifndef Py_DEBUG
527 Py_ssize_t len;
528
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100529 len = _PyUnicode_WSTR_LENGTH(unicode);
530 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100531 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200532 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100533 }
534
535 if (len == 1) {
536 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100537 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100538 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
539 Py_DECREF(unicode);
540 return latin1_char;
541 }
542 }
543
544 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200545 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100546 return NULL;
547 }
548#else
Victor Stinneraa771272012-10-04 02:32:58 +0200549 assert(Py_REFCNT(unicode) == 1);
550
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100551 /* don't make the result ready in debug mode to ensure that the caller
552 makes the string ready before using it */
553 assert(_PyUnicode_CheckConsistency(unicode, 1));
554#endif
555 return unicode;
556}
557
558static PyObject*
559unicode_result_ready(PyObject *unicode)
560{
561 Py_ssize_t length;
562
563 length = PyUnicode_GET_LENGTH(unicode);
564 if (length == 0) {
565 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100566 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200567 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100568 }
569 return unicode_empty;
570 }
571
572 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200573 void *data = PyUnicode_DATA(unicode);
574 int kind = PyUnicode_KIND(unicode);
575 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100576 if (ch < 256) {
577 PyObject *latin1_char = unicode_latin1[ch];
578 if (latin1_char != NULL) {
579 if (unicode != latin1_char) {
580 Py_INCREF(latin1_char);
581 Py_DECREF(unicode);
582 }
583 return latin1_char;
584 }
585 else {
586 assert(_PyUnicode_CheckConsistency(unicode, 1));
587 Py_INCREF(unicode);
588 unicode_latin1[ch] = unicode;
589 return unicode;
590 }
591 }
592 }
593
594 assert(_PyUnicode_CheckConsistency(unicode, 1));
595 return unicode;
596}
597
598static PyObject*
599unicode_result(PyObject *unicode)
600{
601 assert(_PyUnicode_CHECK(unicode));
602 if (PyUnicode_IS_READY(unicode))
603 return unicode_result_ready(unicode);
604 else
605 return unicode_result_wchar(unicode);
606}
607
Victor Stinnerc4b49542011-12-11 22:44:26 +0100608static PyObject*
609unicode_result_unchanged(PyObject *unicode)
610{
611 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500612 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100613 return NULL;
614 Py_INCREF(unicode);
615 return unicode;
616 }
617 else
618 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100619 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100620}
621
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200622/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
623 ASCII, Latin1, UTF-8, etc. */
624static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200625backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200626 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
627{
Victor Stinnerad771582015-10-09 12:38:53 +0200628 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200629 Py_UCS4 ch;
630 enum PyUnicode_Kind kind;
631 void *data;
632
633 assert(PyUnicode_IS_READY(unicode));
634 kind = PyUnicode_KIND(unicode);
635 data = PyUnicode_DATA(unicode);
636
637 size = 0;
638 /* determine replacement size */
639 for (i = collstart; i < collend; ++i) {
640 Py_ssize_t incr;
641
642 ch = PyUnicode_READ(kind, data, i);
643 if (ch < 0x100)
644 incr = 2+2;
645 else if (ch < 0x10000)
646 incr = 2+4;
647 else {
648 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200649 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200650 }
651 if (size > PY_SSIZE_T_MAX - incr) {
652 PyErr_SetString(PyExc_OverflowError,
653 "encoded result is too long for a Python string");
654 return NULL;
655 }
656 size += incr;
657 }
658
Victor Stinnerad771582015-10-09 12:38:53 +0200659 str = _PyBytesWriter_Prepare(writer, str, size);
660 if (str == NULL)
661 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200662
663 /* generate replacement */
664 for (i = collstart; i < collend; ++i) {
665 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200666 *str++ = '\\';
667 if (ch >= 0x00010000) {
668 *str++ = 'U';
669 *str++ = Py_hexdigits[(ch>>28)&0xf];
670 *str++ = Py_hexdigits[(ch>>24)&0xf];
671 *str++ = Py_hexdigits[(ch>>20)&0xf];
672 *str++ = Py_hexdigits[(ch>>16)&0xf];
673 *str++ = Py_hexdigits[(ch>>12)&0xf];
674 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200675 }
Victor Stinner797485e2015-10-09 03:17:30 +0200676 else if (ch >= 0x100) {
677 *str++ = 'u';
678 *str++ = Py_hexdigits[(ch>>12)&0xf];
679 *str++ = Py_hexdigits[(ch>>8)&0xf];
680 }
681 else
682 *str++ = 'x';
683 *str++ = Py_hexdigits[(ch>>4)&0xf];
684 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200685 }
686 return str;
687}
688
689/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
690 ASCII, Latin1, UTF-8, etc. */
691static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200692xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200693 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
694{
Victor Stinnerad771582015-10-09 12:38:53 +0200695 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200696 Py_UCS4 ch;
697 enum PyUnicode_Kind kind;
698 void *data;
699
700 assert(PyUnicode_IS_READY(unicode));
701 kind = PyUnicode_KIND(unicode);
702 data = PyUnicode_DATA(unicode);
703
704 size = 0;
705 /* determine replacement size */
706 for (i = collstart; i < collend; ++i) {
707 Py_ssize_t incr;
708
709 ch = PyUnicode_READ(kind, data, i);
710 if (ch < 10)
711 incr = 2+1+1;
712 else if (ch < 100)
713 incr = 2+2+1;
714 else if (ch < 1000)
715 incr = 2+3+1;
716 else if (ch < 10000)
717 incr = 2+4+1;
718 else if (ch < 100000)
719 incr = 2+5+1;
720 else if (ch < 1000000)
721 incr = 2+6+1;
722 else {
723 assert(ch <= MAX_UNICODE);
724 incr = 2+7+1;
725 }
726 if (size > PY_SSIZE_T_MAX - incr) {
727 PyErr_SetString(PyExc_OverflowError,
728 "encoded result is too long for a Python string");
729 return NULL;
730 }
731 size += incr;
732 }
733
Victor Stinnerad771582015-10-09 12:38:53 +0200734 str = _PyBytesWriter_Prepare(writer, str, size);
735 if (str == NULL)
736 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200737
738 /* generate replacement */
739 for (i = collstart; i < collend; ++i) {
740 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
741 }
742 return str;
743}
744
Thomas Wouters477c8d52006-05-27 19:21:47 +0000745/* --- Bloom Filters ----------------------------------------------------- */
746
747/* stuff to implement simple "bloom filters" for Unicode characters.
748 to keep things simple, we use a single bitmask, using the least 5
749 bits from each unicode characters as the bit index. */
750
751/* the linebreak mask is set up by Unicode_Init below */
752
Antoine Pitrouf068f942010-01-13 14:19:12 +0000753#if LONG_BIT >= 128
754#define BLOOM_WIDTH 128
755#elif LONG_BIT >= 64
756#define BLOOM_WIDTH 64
757#elif LONG_BIT >= 32
758#define BLOOM_WIDTH 32
759#else
760#error "LONG_BIT is smaller than 32"
761#endif
762
Thomas Wouters477c8d52006-05-27 19:21:47 +0000763#define BLOOM_MASK unsigned long
764
Serhiy Storchaka05997252013-01-26 12:14:02 +0200765static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000766
Antoine Pitrouf068f942010-01-13 14:19:12 +0000767#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768
Benjamin Peterson29060642009-01-31 22:14:21 +0000769#define BLOOM_LINEBREAK(ch) \
770 ((ch) < 128U ? ascii_linebreak[(ch)] : \
771 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000772
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700773static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200774make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000775{
Victor Stinnera85af502013-04-09 21:53:54 +0200776#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
777 do { \
778 TYPE *data = (TYPE *)PTR; \
779 TYPE *end = data + LEN; \
780 Py_UCS4 ch; \
781 for (; data != end; data++) { \
782 ch = *data; \
783 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
784 } \
785 break; \
786 } while (0)
787
Thomas Wouters477c8d52006-05-27 19:21:47 +0000788 /* calculate simple bloom-style bitmask for a given unicode string */
789
Antoine Pitrouf068f942010-01-13 14:19:12 +0000790 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000791
792 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200793 switch (kind) {
794 case PyUnicode_1BYTE_KIND:
795 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
796 break;
797 case PyUnicode_2BYTE_KIND:
798 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
799 break;
800 case PyUnicode_4BYTE_KIND:
801 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
802 break;
803 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700804 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200805 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000806 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200807
808#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809}
810
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300811static int
812ensure_unicode(PyObject *obj)
813{
814 if (!PyUnicode_Check(obj)) {
815 PyErr_Format(PyExc_TypeError,
816 "must be str, not %.100s",
817 Py_TYPE(obj)->tp_name);
818 return -1;
819 }
820 return PyUnicode_READY(obj);
821}
822
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200823/* Compilation of templated routines */
824
825#include "stringlib/asciilib.h"
826#include "stringlib/fastsearch.h"
827#include "stringlib/partition.h"
828#include "stringlib/split.h"
829#include "stringlib/count.h"
830#include "stringlib/find.h"
831#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200832#include "stringlib/undef.h"
833
834#include "stringlib/ucs1lib.h"
835#include "stringlib/fastsearch.h"
836#include "stringlib/partition.h"
837#include "stringlib/split.h"
838#include "stringlib/count.h"
839#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300840#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200841#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200842#include "stringlib/undef.h"
843
844#include "stringlib/ucs2lib.h"
845#include "stringlib/fastsearch.h"
846#include "stringlib/partition.h"
847#include "stringlib/split.h"
848#include "stringlib/count.h"
849#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300850#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200851#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200852#include "stringlib/undef.h"
853
854#include "stringlib/ucs4lib.h"
855#include "stringlib/fastsearch.h"
856#include "stringlib/partition.h"
857#include "stringlib/split.h"
858#include "stringlib/count.h"
859#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300860#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200861#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200862#include "stringlib/undef.h"
863
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200864#include "stringlib/unicodedefs.h"
865#include "stringlib/fastsearch.h"
866#include "stringlib/count.h"
867#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100868#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200869
Guido van Rossumd57fd912000-03-10 22:53:23 +0000870/* --- Unicode Object ----------------------------------------------------- */
871
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700872static inline Py_ssize_t
873findchar(const void *s, int kind,
874 Py_ssize_t size, Py_UCS4 ch,
875 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200876{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200877 switch (kind) {
878 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200879 if ((Py_UCS1) ch != ch)
880 return -1;
881 if (direction > 0)
882 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
883 else
884 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200885 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200886 if ((Py_UCS2) ch != ch)
887 return -1;
888 if (direction > 0)
889 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
890 else
891 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200892 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200893 if (direction > 0)
894 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
895 else
896 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200897 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700898 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200899 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900}
901
Victor Stinnerafffce42012-10-03 23:03:17 +0200902#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000903/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200904 earlier.
905
906 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
907 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
908 invalid character in Unicode 6.0. */
909static void
910unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
911{
912 int kind = PyUnicode_KIND(unicode);
913 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
914 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
915 if (length <= old_length)
916 return;
917 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
918}
919#endif
920
Victor Stinnerfe226c02011-10-03 03:52:20 +0200921static PyObject*
922resize_compact(PyObject *unicode, Py_ssize_t length)
923{
924 Py_ssize_t char_size;
925 Py_ssize_t struct_size;
926 Py_ssize_t new_size;
927 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100928 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200929#ifdef Py_DEBUG
930 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
931#endif
932
Victor Stinner79891572012-05-03 13:43:07 +0200933 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200934 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100935 assert(PyUnicode_IS_COMPACT(unicode));
936
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200937 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100938 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200939 struct_size = sizeof(PyASCIIObject);
940 else
941 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200943
Victor Stinnerfe226c02011-10-03 03:52:20 +0200944 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
945 PyErr_NoMemory();
946 return NULL;
947 }
948 new_size = (struct_size + (length + 1) * char_size);
949
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200950 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
951 PyObject_DEL(_PyUnicode_UTF8(unicode));
952 _PyUnicode_UTF8(unicode) = NULL;
953 _PyUnicode_UTF8_LENGTH(unicode) = 0;
954 }
Victor Stinner84def372011-12-11 20:04:56 +0100955 _Py_DEC_REFTOTAL;
956 _Py_ForgetReference(unicode);
957
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300958 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100959 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100960 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200961 PyErr_NoMemory();
962 return NULL;
963 }
Victor Stinner84def372011-12-11 20:04:56 +0100964 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100966
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200968 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200969 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100970 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200971 _PyUnicode_WSTR_LENGTH(unicode) = length;
972 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100973 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
974 PyObject_DEL(_PyUnicode_WSTR(unicode));
975 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100976 if (!PyUnicode_IS_ASCII(unicode))
977 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100978 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200979#ifdef Py_DEBUG
980 unicode_fill_invalid(unicode, old_length);
981#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200982 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
983 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200984 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200985 return unicode;
986}
987
Alexander Belopolsky40018472011-02-26 01:02:56 +0000988static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200989resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000990{
Victor Stinner95663112011-10-04 01:03:50 +0200991 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100992 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200994 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000995
Victor Stinnerfe226c02011-10-03 03:52:20 +0200996 if (PyUnicode_IS_READY(unicode)) {
997 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200998 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200999 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +02001000#ifdef Py_DEBUG
1001 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1002#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003
1004 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001005 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001006 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
1007 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001008
1009 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1010 PyErr_NoMemory();
1011 return -1;
1012 }
1013 new_size = (length + 1) * char_size;
1014
Victor Stinner7a9105a2011-12-12 00:13:42 +01001015 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1016 {
1017 PyObject_DEL(_PyUnicode_UTF8(unicode));
1018 _PyUnicode_UTF8(unicode) = NULL;
1019 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1020 }
1021
Victor Stinnerfe226c02011-10-03 03:52:20 +02001022 data = (PyObject *)PyObject_REALLOC(data, new_size);
1023 if (data == NULL) {
1024 PyErr_NoMemory();
1025 return -1;
1026 }
1027 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001028 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001029 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001030 _PyUnicode_WSTR_LENGTH(unicode) = length;
1031 }
1032 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001033 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001034 _PyUnicode_UTF8_LENGTH(unicode) = length;
1035 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001036 _PyUnicode_LENGTH(unicode) = length;
1037 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001038#ifdef Py_DEBUG
1039 unicode_fill_invalid(unicode, old_length);
1040#endif
Victor Stinner95663112011-10-04 01:03:50 +02001041 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001042 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001044 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001045 }
Victor Stinner95663112011-10-04 01:03:50 +02001046 assert(_PyUnicode_WSTR(unicode) != NULL);
1047
1048 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001049 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001050 PyErr_NoMemory();
1051 return -1;
1052 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001053 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001054 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001055 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001056 if (!wstr) {
1057 PyErr_NoMemory();
1058 return -1;
1059 }
1060 _PyUnicode_WSTR(unicode) = wstr;
1061 _PyUnicode_WSTR(unicode)[length] = 0;
1062 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001063 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001064 return 0;
1065}
1066
Victor Stinnerfe226c02011-10-03 03:52:20 +02001067static PyObject*
1068resize_copy(PyObject *unicode, Py_ssize_t length)
1069{
1070 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001071 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001072 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001073
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001074 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001075
1076 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1077 if (copy == NULL)
1078 return NULL;
1079
1080 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001081 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001082 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001083 }
1084 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001085 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001086
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001087 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001088 if (w == NULL)
1089 return NULL;
1090 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1091 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001092 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001093 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001094 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001095 }
1096}
1097
Guido van Rossumd57fd912000-03-10 22:53:23 +00001098/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001099 Ux0000 terminated; some code (e.g. new_identifier)
1100 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001101
1102 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001103 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001104
1105*/
1106
Alexander Belopolsky40018472011-02-26 01:02:56 +00001107static PyUnicodeObject *
1108_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001109{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001110 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001112
Thomas Wouters477c8d52006-05-27 19:21:47 +00001113 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001114 if (length == 0 && unicode_empty != NULL) {
1115 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001116 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001117 }
1118
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001119 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001120 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001121 return (PyUnicodeObject *)PyErr_NoMemory();
1122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 if (length < 0) {
1124 PyErr_SetString(PyExc_SystemError,
1125 "Negative size passed to _PyUnicode_New");
1126 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001127 }
1128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1130 if (unicode == NULL)
1131 return NULL;
1132 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001133
1134 _PyUnicode_WSTR_LENGTH(unicode) = length;
1135 _PyUnicode_HASH(unicode) = -1;
1136 _PyUnicode_STATE(unicode).interned = 0;
1137 _PyUnicode_STATE(unicode).kind = 0;
1138 _PyUnicode_STATE(unicode).compact = 0;
1139 _PyUnicode_STATE(unicode).ready = 0;
1140 _PyUnicode_STATE(unicode).ascii = 0;
1141 _PyUnicode_DATA_ANY(unicode) = NULL;
1142 _PyUnicode_LENGTH(unicode) = 0;
1143 _PyUnicode_UTF8(unicode) = NULL;
1144 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1147 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001148 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001149 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001150 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001151 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152
Jeremy Hyltond8082792003-09-16 19:41:39 +00001153 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001154 * the caller fails before initializing str -- unicode_resize()
1155 * reads str[0], and the Keep-Alive optimization can keep memory
1156 * allocated for str alive across a call to unicode_dealloc(unicode).
1157 * We don't want unicode_resize to read uninitialized memory in
1158 * that case.
1159 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001160 _PyUnicode_WSTR(unicode)[0] = 0;
1161 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001162
Victor Stinner7931d9a2011-11-04 00:22:48 +01001163 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001164 return unicode;
1165}
1166
Victor Stinnerf42dc442011-10-02 23:33:16 +02001167static const char*
1168unicode_kind_name(PyObject *unicode)
1169{
Victor Stinner42dfd712011-10-03 14:41:45 +02001170 /* don't check consistency: unicode_kind_name() is called from
1171 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001172 if (!PyUnicode_IS_COMPACT(unicode))
1173 {
1174 if (!PyUnicode_IS_READY(unicode))
1175 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001176 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001177 {
1178 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001179 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001180 return "legacy ascii";
1181 else
1182 return "legacy latin1";
1183 case PyUnicode_2BYTE_KIND:
1184 return "legacy UCS2";
1185 case PyUnicode_4BYTE_KIND:
1186 return "legacy UCS4";
1187 default:
1188 return "<legacy invalid kind>";
1189 }
1190 }
1191 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001192 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001193 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001194 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001195 return "ascii";
1196 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001197 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001198 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001199 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001200 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001201 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001202 default:
1203 return "<invalid compact kind>";
1204 }
1205}
1206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208/* Functions wrapping macros for use in debugger */
1209char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001210 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211}
1212
1213void *_PyUnicode_compact_data(void *unicode) {
1214 return _PyUnicode_COMPACT_DATA(unicode);
1215}
1216void *_PyUnicode_data(void *unicode){
1217 printf("obj %p\n", unicode);
1218 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1219 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1220 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1221 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1222 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1223 return PyUnicode_DATA(unicode);
1224}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001225
1226void
1227_PyUnicode_Dump(PyObject *op)
1228{
1229 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001230 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1231 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1232 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001233
Victor Stinnera849a4b2011-10-03 12:12:11 +02001234 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001235 {
1236 if (ascii->state.ascii)
1237 data = (ascii + 1);
1238 else
1239 data = (compact + 1);
1240 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001241 else
1242 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001243 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1244 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001245
Victor Stinnera849a4b2011-10-03 12:12:11 +02001246 if (ascii->wstr == data)
1247 printf("shared ");
1248 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001249
Victor Stinnera3b334d2011-10-03 13:53:37 +02001250 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001251 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001252 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1253 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001254 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1255 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001256 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001257 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001258}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001259#endif
1260
1261PyObject *
1262PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1263{
1264 PyObject *obj;
1265 PyCompactUnicodeObject *unicode;
1266 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001267 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001268 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001269 Py_ssize_t char_size;
1270 Py_ssize_t struct_size;
1271
1272 /* Optimization for empty strings */
1273 if (size == 0 && unicode_empty != NULL) {
1274 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001275 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 }
1277
Victor Stinner9e9d6892011-10-04 01:02:02 +02001278 is_ascii = 0;
1279 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001280 struct_size = sizeof(PyCompactUnicodeObject);
1281 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001282 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001283 char_size = 1;
1284 is_ascii = 1;
1285 struct_size = sizeof(PyASCIIObject);
1286 }
1287 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001288 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001289 char_size = 1;
1290 }
1291 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001292 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001293 char_size = 2;
1294 if (sizeof(wchar_t) == 2)
1295 is_sharing = 1;
1296 }
1297 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001298 if (maxchar > MAX_UNICODE) {
1299 PyErr_SetString(PyExc_SystemError,
1300 "invalid maximum character passed to PyUnicode_New");
1301 return NULL;
1302 }
Victor Stinner8f825062012-04-27 13:55:39 +02001303 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 char_size = 4;
1305 if (sizeof(wchar_t) == 4)
1306 is_sharing = 1;
1307 }
1308
1309 /* Ensure we won't overflow the size. */
1310 if (size < 0) {
1311 PyErr_SetString(PyExc_SystemError,
1312 "Negative size passed to PyUnicode_New");
1313 return NULL;
1314 }
1315 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1316 return PyErr_NoMemory();
1317
1318 /* Duplicated allocation code from _PyObject_New() instead of a call to
1319 * PyObject_New() so we are able to allocate space for the object and
1320 * it's data buffer.
1321 */
1322 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1323 if (obj == NULL)
1324 return PyErr_NoMemory();
1325 obj = PyObject_INIT(obj, &PyUnicode_Type);
1326 if (obj == NULL)
1327 return NULL;
1328
1329 unicode = (PyCompactUnicodeObject *)obj;
1330 if (is_ascii)
1331 data = ((PyASCIIObject*)obj) + 1;
1332 else
1333 data = unicode + 1;
1334 _PyUnicode_LENGTH(unicode) = size;
1335 _PyUnicode_HASH(unicode) = -1;
1336 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001337 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 _PyUnicode_STATE(unicode).compact = 1;
1339 _PyUnicode_STATE(unicode).ready = 1;
1340 _PyUnicode_STATE(unicode).ascii = is_ascii;
1341 if (is_ascii) {
1342 ((char*)data)[size] = 0;
1343 _PyUnicode_WSTR(unicode) = NULL;
1344 }
Victor Stinner8f825062012-04-27 13:55:39 +02001345 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346 ((char*)data)[size] = 0;
1347 _PyUnicode_WSTR(unicode) = NULL;
1348 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001350 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352 else {
1353 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001354 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001355 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001357 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 ((Py_UCS4*)data)[size] = 0;
1359 if (is_sharing) {
1360 _PyUnicode_WSTR_LENGTH(unicode) = size;
1361 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1362 }
1363 else {
1364 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1365 _PyUnicode_WSTR(unicode) = NULL;
1366 }
1367 }
Victor Stinner8f825062012-04-27 13:55:39 +02001368#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001369 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001370#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001371 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372 return obj;
1373}
1374
1375#if SIZEOF_WCHAR_T == 2
1376/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1377 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001378 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001379
1380 This function assumes that unicode can hold one more code point than wstr
1381 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001382static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001384 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001385{
1386 const wchar_t *iter;
1387 Py_UCS4 *ucs4_out;
1388
Victor Stinner910337b2011-10-03 03:20:16 +02001389 assert(unicode != NULL);
1390 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1392 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1393
1394 for (iter = begin; iter < end; ) {
1395 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1396 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001397 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1398 && (iter+1) < end
1399 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 {
Victor Stinner551ac952011-11-29 22:58:13 +01001401 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402 iter += 2;
1403 }
1404 else {
1405 *ucs4_out++ = *iter;
1406 iter++;
1407 }
1408 }
1409 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1410 _PyUnicode_GET_LENGTH(unicode)));
1411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412}
1413#endif
1414
Victor Stinnercd9950f2011-10-02 00:34:53 +02001415static int
Victor Stinner488fa492011-12-12 00:01:39 +01001416unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001417{
Victor Stinner488fa492011-12-12 00:01:39 +01001418 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001419 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001420 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001421 return -1;
1422 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001423 return 0;
1424}
1425
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001426static int
1427_copy_characters(PyObject *to, Py_ssize_t to_start,
1428 PyObject *from, Py_ssize_t from_start,
1429 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001431 unsigned int from_kind, to_kind;
1432 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433
Victor Stinneree4544c2012-05-09 22:24:08 +02001434 assert(0 <= how_many);
1435 assert(0 <= from_start);
1436 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001437 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001438 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001439 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440
Victor Stinnerd3f08822012-05-29 12:57:52 +02001441 assert(PyUnicode_Check(to));
1442 assert(PyUnicode_IS_READY(to));
1443 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1444
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001445 if (how_many == 0)
1446 return 0;
1447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001449 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001451 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452
Victor Stinnerf1852262012-06-16 16:38:26 +02001453#ifdef Py_DEBUG
1454 if (!check_maxchar
1455 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1456 {
1457 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1458 Py_UCS4 ch;
1459 Py_ssize_t i;
1460 for (i=0; i < how_many; i++) {
1461 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1462 assert(ch <= to_maxchar);
1463 }
1464 }
1465#endif
1466
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001467 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001468 if (check_maxchar
1469 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1470 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001471 /* Writing Latin-1 characters into an ASCII string requires to
1472 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001473 Py_UCS4 max_char;
1474 max_char = ucs1lib_find_max_char(from_data,
1475 (Py_UCS1*)from_data + how_many);
1476 if (max_char >= 128)
1477 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001478 }
Christian Heimesf051e432016-09-13 20:22:02 +02001479 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001480 (char*)from_data + from_kind * from_start,
1481 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001482 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001483 else if (from_kind == PyUnicode_1BYTE_KIND
1484 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001485 {
1486 _PyUnicode_CONVERT_BYTES(
1487 Py_UCS1, Py_UCS2,
1488 PyUnicode_1BYTE_DATA(from) + from_start,
1489 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1490 PyUnicode_2BYTE_DATA(to) + to_start
1491 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001492 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001493 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001494 && to_kind == PyUnicode_4BYTE_KIND)
1495 {
1496 _PyUnicode_CONVERT_BYTES(
1497 Py_UCS1, Py_UCS4,
1498 PyUnicode_1BYTE_DATA(from) + from_start,
1499 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1500 PyUnicode_4BYTE_DATA(to) + to_start
1501 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001502 }
1503 else if (from_kind == PyUnicode_2BYTE_KIND
1504 && to_kind == PyUnicode_4BYTE_KIND)
1505 {
1506 _PyUnicode_CONVERT_BYTES(
1507 Py_UCS2, Py_UCS4,
1508 PyUnicode_2BYTE_DATA(from) + from_start,
1509 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1510 PyUnicode_4BYTE_DATA(to) + to_start
1511 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001512 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001514 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1515
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001516 if (!check_maxchar) {
1517 if (from_kind == PyUnicode_2BYTE_KIND
1518 && to_kind == PyUnicode_1BYTE_KIND)
1519 {
1520 _PyUnicode_CONVERT_BYTES(
1521 Py_UCS2, Py_UCS1,
1522 PyUnicode_2BYTE_DATA(from) + from_start,
1523 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1524 PyUnicode_1BYTE_DATA(to) + to_start
1525 );
1526 }
1527 else if (from_kind == PyUnicode_4BYTE_KIND
1528 && to_kind == PyUnicode_1BYTE_KIND)
1529 {
1530 _PyUnicode_CONVERT_BYTES(
1531 Py_UCS4, Py_UCS1,
1532 PyUnicode_4BYTE_DATA(from) + from_start,
1533 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1534 PyUnicode_1BYTE_DATA(to) + to_start
1535 );
1536 }
1537 else if (from_kind == PyUnicode_4BYTE_KIND
1538 && to_kind == PyUnicode_2BYTE_KIND)
1539 {
1540 _PyUnicode_CONVERT_BYTES(
1541 Py_UCS4, Py_UCS2,
1542 PyUnicode_4BYTE_DATA(from) + from_start,
1543 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1544 PyUnicode_2BYTE_DATA(to) + to_start
1545 );
1546 }
1547 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001548 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001549 }
1550 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001551 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001552 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001553 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001554 Py_ssize_t i;
1555
Victor Stinnera0702ab2011-09-29 14:14:38 +02001556 for (i=0; i < how_many; i++) {
1557 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001558 if (ch > to_maxchar)
1559 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001560 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1561 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001562 }
1563 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 return 0;
1565}
1566
Victor Stinnerd3f08822012-05-29 12:57:52 +02001567void
1568_PyUnicode_FastCopyCharacters(
1569 PyObject *to, Py_ssize_t to_start,
1570 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001571{
1572 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1573}
1574
1575Py_ssize_t
1576PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1577 PyObject *from, Py_ssize_t from_start,
1578 Py_ssize_t how_many)
1579{
1580 int err;
1581
1582 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1583 PyErr_BadInternalCall();
1584 return -1;
1585 }
1586
Benjamin Petersonbac79492012-01-14 13:34:47 -05001587 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001588 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001589 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001590 return -1;
1591
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001592 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001593 PyErr_SetString(PyExc_IndexError, "string index out of range");
1594 return -1;
1595 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001596 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001597 PyErr_SetString(PyExc_IndexError, "string index out of range");
1598 return -1;
1599 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001600 if (how_many < 0) {
1601 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1602 return -1;
1603 }
1604 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001605 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1606 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001607 "Cannot write %zi characters at %zi "
1608 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001609 how_many, to_start, PyUnicode_GET_LENGTH(to));
1610 return -1;
1611 }
1612
1613 if (how_many == 0)
1614 return 0;
1615
Victor Stinner488fa492011-12-12 00:01:39 +01001616 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001617 return -1;
1618
1619 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1620 if (err) {
1621 PyErr_Format(PyExc_SystemError,
1622 "Cannot copy %s characters "
1623 "into a string of %s characters",
1624 unicode_kind_name(from),
1625 unicode_kind_name(to));
1626 return -1;
1627 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001628 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629}
1630
Victor Stinner17222162011-09-28 22:15:37 +02001631/* Find the maximum code point and count the number of surrogate pairs so a
1632 correct string length can be computed before converting a string to UCS4.
1633 This function counts single surrogates as a character and not as a pair.
1634
1635 Return 0 on success, or -1 on error. */
1636static int
1637find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1638 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639{
1640 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001641 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642
Victor Stinnerc53be962011-10-02 21:33:54 +02001643 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001644 *num_surrogates = 0;
1645 *maxchar = 0;
1646
1647 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001648#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001649 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1650 && (iter+1) < end
1651 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1652 {
1653 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1654 ++(*num_surrogates);
1655 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656 }
1657 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001659 {
1660 ch = *iter;
1661 iter++;
1662 }
1663 if (ch > *maxchar) {
1664 *maxchar = ch;
1665 if (*maxchar > MAX_UNICODE) {
1666 PyErr_Format(PyExc_ValueError,
1667 "character U+%x is not in range [U+0000; U+10ffff]",
1668 ch);
1669 return -1;
1670 }
1671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 }
1673 return 0;
1674}
1675
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001676int
1677_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001678{
1679 wchar_t *end;
1680 Py_UCS4 maxchar = 0;
1681 Py_ssize_t num_surrogates;
1682#if SIZEOF_WCHAR_T == 2
1683 Py_ssize_t length_wo_surrogates;
1684#endif
1685
Georg Brandl7597add2011-10-05 16:36:47 +02001686 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001687 strings were created using _PyObject_New() and where no canonical
1688 representation (the str field) has been set yet aka strings
1689 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001690 assert(_PyUnicode_CHECK(unicode));
1691 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001693 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001694 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001695 /* Actually, it should neither be interned nor be anything else: */
1696 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001699 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001700 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001701 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001702
1703 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001704 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1705 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 PyErr_NoMemory();
1707 return -1;
1708 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001709 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 _PyUnicode_WSTR(unicode), end,
1711 PyUnicode_1BYTE_DATA(unicode));
1712 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1713 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1714 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1715 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001716 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001717 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001718 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 }
1720 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001721 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001722 _PyUnicode_UTF8(unicode) = NULL;
1723 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 }
1725 PyObject_FREE(_PyUnicode_WSTR(unicode));
1726 _PyUnicode_WSTR(unicode) = NULL;
1727 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1728 }
1729 /* In this case we might have to convert down from 4-byte native
1730 wchar_t to 2-byte unicode. */
1731 else if (maxchar < 65536) {
1732 assert(num_surrogates == 0 &&
1733 "FindMaxCharAndNumSurrogatePairs() messed up");
1734
Victor Stinner506f5922011-09-28 22:34:18 +02001735#if SIZEOF_WCHAR_T == 2
1736 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001737 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001738 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1739 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1740 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001741 _PyUnicode_UTF8(unicode) = NULL;
1742 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001743#else
1744 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001745 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001746 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001747 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001748 PyErr_NoMemory();
1749 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 }
Victor Stinner506f5922011-09-28 22:34:18 +02001751 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1752 _PyUnicode_WSTR(unicode), end,
1753 PyUnicode_2BYTE_DATA(unicode));
1754 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1755 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1756 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001757 _PyUnicode_UTF8(unicode) = NULL;
1758 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001759 PyObject_FREE(_PyUnicode_WSTR(unicode));
1760 _PyUnicode_WSTR(unicode) = NULL;
1761 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1762#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001763 }
1764 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1765 else {
1766#if SIZEOF_WCHAR_T == 2
1767 /* in case the native representation is 2-bytes, we need to allocate a
1768 new normalized 4-byte version. */
1769 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001770 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1771 PyErr_NoMemory();
1772 return -1;
1773 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001774 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1775 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001776 PyErr_NoMemory();
1777 return -1;
1778 }
1779 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1780 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001781 _PyUnicode_UTF8(unicode) = NULL;
1782 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001783 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1784 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001785 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001786 PyObject_FREE(_PyUnicode_WSTR(unicode));
1787 _PyUnicode_WSTR(unicode) = NULL;
1788 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1789#else
1790 assert(num_surrogates == 0);
1791
Victor Stinnerc3c74152011-10-02 20:39:55 +02001792 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001794 _PyUnicode_UTF8(unicode) = NULL;
1795 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1797#endif
1798 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1799 }
1800 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001801 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 return 0;
1803}
1804
Alexander Belopolsky40018472011-02-26 01:02:56 +00001805static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001806unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807{
Walter Dörwald16807132007-05-25 13:52:07 +00001808 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001809 case SSTATE_NOT_INTERNED:
1810 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001811
Benjamin Peterson29060642009-01-31 22:14:21 +00001812 case SSTATE_INTERNED_MORTAL:
1813 /* revive dead object temporarily for DelItem */
1814 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001815 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001816 Py_FatalError(
1817 "deletion of interned string failed");
1818 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001819
Benjamin Peterson29060642009-01-31 22:14:21 +00001820 case SSTATE_INTERNED_IMMORTAL:
1821 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001822 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001823
Benjamin Peterson29060642009-01-31 22:14:21 +00001824 default:
1825 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001826 }
1827
Victor Stinner03490912011-10-03 23:45:12 +02001828 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001829 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001830 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001831 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001832 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1833 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001834
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001835 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001836}
1837
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001838#ifdef Py_DEBUG
1839static int
1840unicode_is_singleton(PyObject *unicode)
1841{
1842 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1843 if (unicode == unicode_empty)
1844 return 1;
1845 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1846 {
1847 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1848 if (ch < 256 && unicode_latin1[ch] == unicode)
1849 return 1;
1850 }
1851 return 0;
1852}
1853#endif
1854
Alexander Belopolsky40018472011-02-26 01:02:56 +00001855static int
Victor Stinner488fa492011-12-12 00:01:39 +01001856unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001857{
Victor Stinner488fa492011-12-12 00:01:39 +01001858 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 if (Py_REFCNT(unicode) != 1)
1860 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001861 if (_PyUnicode_HASH(unicode) != -1)
1862 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001863 if (PyUnicode_CHECK_INTERNED(unicode))
1864 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001865 if (!PyUnicode_CheckExact(unicode))
1866 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001867#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001868 /* singleton refcount is greater than 1 */
1869 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001870#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001871 return 1;
1872}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001873
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874static int
1875unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1876{
1877 PyObject *unicode;
1878 Py_ssize_t old_length;
1879
1880 assert(p_unicode != NULL);
1881 unicode = *p_unicode;
1882
1883 assert(unicode != NULL);
1884 assert(PyUnicode_Check(unicode));
1885 assert(0 <= length);
1886
Victor Stinner910337b2011-10-03 03:20:16 +02001887 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001888 old_length = PyUnicode_WSTR_LENGTH(unicode);
1889 else
1890 old_length = PyUnicode_GET_LENGTH(unicode);
1891 if (old_length == length)
1892 return 0;
1893
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001894 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001895 _Py_INCREF_UNICODE_EMPTY();
1896 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001897 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001898 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001899 return 0;
1900 }
1901
Victor Stinner488fa492011-12-12 00:01:39 +01001902 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001903 PyObject *copy = resize_copy(unicode, length);
1904 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001905 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001906 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001907 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001908 }
1909
Victor Stinnerfe226c02011-10-03 03:52:20 +02001910 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001911 PyObject *new_unicode = resize_compact(unicode, length);
1912 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001913 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001914 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001915 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001916 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001917 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001918}
1919
Alexander Belopolsky40018472011-02-26 01:02:56 +00001920int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001921PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001922{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001923 PyObject *unicode;
1924 if (p_unicode == NULL) {
1925 PyErr_BadInternalCall();
1926 return -1;
1927 }
1928 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001929 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001930 {
1931 PyErr_BadInternalCall();
1932 return -1;
1933 }
1934 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001935}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001936
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001937/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001938
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001939 WARNING: The function doesn't copy the terminating null character and
1940 doesn't check the maximum character (may write a latin1 character in an
1941 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001942static void
1943unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1944 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001945{
1946 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1947 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001948 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001949
1950 switch (kind) {
1951 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001952 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001953#ifdef Py_DEBUG
1954 if (PyUnicode_IS_ASCII(unicode)) {
1955 Py_UCS4 maxchar = ucs1lib_find_max_char(
1956 (const Py_UCS1*)str,
1957 (const Py_UCS1*)str + len);
1958 assert(maxchar < 128);
1959 }
1960#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001961 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001962 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001963 }
1964 case PyUnicode_2BYTE_KIND: {
1965 Py_UCS2 *start = (Py_UCS2 *)data + index;
1966 Py_UCS2 *ucs2 = start;
1967 assert(index <= PyUnicode_GET_LENGTH(unicode));
1968
Victor Stinner184252a2012-06-16 02:57:41 +02001969 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001970 *ucs2 = (Py_UCS2)*str;
1971
1972 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001973 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001974 }
1975 default: {
1976 Py_UCS4 *start = (Py_UCS4 *)data + index;
1977 Py_UCS4 *ucs4 = start;
1978 assert(kind == PyUnicode_4BYTE_KIND);
1979 assert(index <= PyUnicode_GET_LENGTH(unicode));
1980
Victor Stinner184252a2012-06-16 02:57:41 +02001981 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001982 *ucs4 = (Py_UCS4)*str;
1983
1984 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001985 }
1986 }
1987}
1988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989static PyObject*
1990get_latin1_char(unsigned char ch)
1991{
Victor Stinnera464fc12011-10-02 20:39:30 +02001992 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001993 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001994 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995 if (!unicode)
1996 return NULL;
1997 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001998 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 unicode_latin1[ch] = unicode;
2000 }
2001 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02002002 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003}
2004
Victor Stinner985a82a2014-01-03 12:53:47 +01002005static PyObject*
2006unicode_char(Py_UCS4 ch)
2007{
2008 PyObject *unicode;
2009
2010 assert(ch <= MAX_UNICODE);
2011
Victor Stinnerf3b46b42014-01-03 13:16:00 +01002012 if (ch < 256)
2013 return get_latin1_char(ch);
2014
Victor Stinner985a82a2014-01-03 12:53:47 +01002015 unicode = PyUnicode_New(1, ch);
2016 if (unicode == NULL)
2017 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002018
2019 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
2020 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01002021 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002022 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01002023 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2024 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
2025 }
2026 assert(_PyUnicode_CheckConsistency(unicode, 1));
2027 return unicode;
2028}
2029
Alexander Belopolsky40018472011-02-26 01:02:56 +00002030PyObject *
2031PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002032{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002033 if (u == NULL)
2034 return (PyObject*)_PyUnicode_New(size);
2035
2036 if (size < 0) {
2037 PyErr_BadInternalCall();
2038 return NULL;
2039 }
2040
2041 return PyUnicode_FromWideChar(u, size);
2042}
2043
2044PyObject *
2045PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2046{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002047 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 Py_UCS4 maxchar = 0;
2049 Py_ssize_t num_surrogates;
2050
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002051 if (u == NULL && size != 0) {
2052 PyErr_BadInternalCall();
2053 return NULL;
2054 }
2055
2056 if (size == -1) {
2057 size = wcslen(u);
2058 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002059
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002060 /* If the Unicode data is known at construction time, we can apply
2061 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002062
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002064 if (size == 0)
2065 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002067 /* Single character Unicode objects in the Latin-1 range are
2068 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002069 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002070 return get_latin1_char((unsigned char)*u);
2071
2072 /* If not empty and not single character, copy the Unicode data
2073 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002074 if (find_maxchar_surrogates(u, u + size,
2075 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 return NULL;
2077
Victor Stinner8faf8212011-12-08 22:14:11 +01002078 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079 if (!unicode)
2080 return NULL;
2081
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002082 switch (PyUnicode_KIND(unicode)) {
2083 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002084 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002085 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2086 break;
2087 case PyUnicode_2BYTE_KIND:
2088#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002089 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002091 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002092 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2093#endif
2094 break;
2095 case PyUnicode_4BYTE_KIND:
2096#if SIZEOF_WCHAR_T == 2
2097 /* This is the only case which has to process surrogates, thus
2098 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002099 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002100#else
2101 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002102 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002103#endif
2104 break;
2105 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002106 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002107 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002108
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002109 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002110}
2111
Alexander Belopolsky40018472011-02-26 01:02:56 +00002112PyObject *
2113PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002114{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002115 if (size < 0) {
2116 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002117 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002118 return NULL;
2119 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002120 if (u != NULL)
2121 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2122 else
2123 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002124}
2125
Alexander Belopolsky40018472011-02-26 01:02:56 +00002126PyObject *
2127PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002128{
2129 size_t size = strlen(u);
2130 if (size > PY_SSIZE_T_MAX) {
2131 PyErr_SetString(PyExc_OverflowError, "input too long");
2132 return NULL;
2133 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002134 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002135}
2136
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002137PyObject *
2138_PyUnicode_FromId(_Py_Identifier *id)
2139{
2140 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002141 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2142 strlen(id->string),
2143 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002144 if (!id->object)
2145 return NULL;
2146 PyUnicode_InternInPlace(&id->object);
2147 assert(!id->next);
2148 id->next = static_strings;
2149 static_strings = id;
2150 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002151 return id->object;
2152}
2153
2154void
2155_PyUnicode_ClearStaticStrings()
2156{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002157 _Py_Identifier *tmp, *s = static_strings;
2158 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002159 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002160 tmp = s->next;
2161 s->next = NULL;
2162 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002163 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002164 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002165}
2166
Benjamin Peterson0df54292012-03-26 14:50:32 -04002167/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002168
Victor Stinnerd3f08822012-05-29 12:57:52 +02002169PyObject*
2170_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002171{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002172 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002173 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002174 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002175#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002176 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002177#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002178 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002179 }
Victor Stinner785938e2011-12-11 20:09:03 +01002180 unicode = PyUnicode_New(size, 127);
2181 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002182 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002183 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2184 assert(_PyUnicode_CheckConsistency(unicode, 1));
2185 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002186}
2187
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002188static Py_UCS4
2189kind_maxchar_limit(unsigned int kind)
2190{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002191 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002192 case PyUnicode_1BYTE_KIND:
2193 return 0x80;
2194 case PyUnicode_2BYTE_KIND:
2195 return 0x100;
2196 case PyUnicode_4BYTE_KIND:
2197 return 0x10000;
2198 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002199 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002200 }
2201}
2202
Victor Stinner702c7342011-10-05 13:50:52 +02002203static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002204_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002205{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002206 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002207 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002208
Serhiy Storchaka678db842013-01-26 12:16:36 +02002209 if (size == 0)
2210 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002211 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002212 if (size == 1)
2213 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002214
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002215 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002216 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 if (!res)
2218 return NULL;
2219 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002220 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002222}
2223
Victor Stinnere57b1c02011-09-28 22:20:48 +02002224static PyObject*
2225_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002226{
2227 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002228 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002229
Serhiy Storchaka678db842013-01-26 12:16:36 +02002230 if (size == 0)
2231 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002233 if (size == 1)
2234 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002235
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002236 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002237 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002238 if (!res)
2239 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002240 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002242 else {
2243 _PyUnicode_CONVERT_BYTES(
2244 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2245 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002246 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 return res;
2248}
2249
Victor Stinnere57b1c02011-09-28 22:20:48 +02002250static PyObject*
2251_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252{
2253 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002254 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002255
Serhiy Storchaka678db842013-01-26 12:16:36 +02002256 if (size == 0)
2257 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002258 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002259 if (size == 1)
2260 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002261
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002262 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002263 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 if (!res)
2265 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002266 if (max_char < 256)
2267 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2268 PyUnicode_1BYTE_DATA(res));
2269 else if (max_char < 0x10000)
2270 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2271 PyUnicode_2BYTE_DATA(res));
2272 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002274 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 return res;
2276}
2277
2278PyObject*
2279PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2280{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002281 if (size < 0) {
2282 PyErr_SetString(PyExc_ValueError, "size must be positive");
2283 return NULL;
2284 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002285 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002286 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002287 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002288 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002289 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002290 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002291 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002292 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002293 PyErr_SetString(PyExc_SystemError, "invalid kind");
2294 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002295 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002296}
2297
Victor Stinnerece58de2012-04-23 23:36:38 +02002298Py_UCS4
2299_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2300{
2301 enum PyUnicode_Kind kind;
2302 void *startptr, *endptr;
2303
2304 assert(PyUnicode_IS_READY(unicode));
2305 assert(0 <= start);
2306 assert(end <= PyUnicode_GET_LENGTH(unicode));
2307 assert(start <= end);
2308
2309 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2310 return PyUnicode_MAX_CHAR_VALUE(unicode);
2311
2312 if (start == end)
2313 return 127;
2314
Victor Stinner94d558b2012-04-27 22:26:58 +02002315 if (PyUnicode_IS_ASCII(unicode))
2316 return 127;
2317
Victor Stinnerece58de2012-04-23 23:36:38 +02002318 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002319 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002320 endptr = (char *)startptr + end * kind;
2321 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002322 switch(kind) {
2323 case PyUnicode_1BYTE_KIND:
2324 return ucs1lib_find_max_char(startptr, endptr);
2325 case PyUnicode_2BYTE_KIND:
2326 return ucs2lib_find_max_char(startptr, endptr);
2327 case PyUnicode_4BYTE_KIND:
2328 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002329 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002330 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002331 }
2332}
2333
Victor Stinner25a4b292011-10-06 12:31:55 +02002334/* Ensure that a string uses the most efficient storage, if it is not the
2335 case: create a new string with of the right kind. Write NULL into *p_unicode
2336 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002337static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002338unicode_adjust_maxchar(PyObject **p_unicode)
2339{
2340 PyObject *unicode, *copy;
2341 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002342 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002343 unsigned int kind;
2344
2345 assert(p_unicode != NULL);
2346 unicode = *p_unicode;
2347 assert(PyUnicode_IS_READY(unicode));
2348 if (PyUnicode_IS_ASCII(unicode))
2349 return;
2350
2351 len = PyUnicode_GET_LENGTH(unicode);
2352 kind = PyUnicode_KIND(unicode);
2353 if (kind == PyUnicode_1BYTE_KIND) {
2354 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002355 max_char = ucs1lib_find_max_char(u, u + len);
2356 if (max_char >= 128)
2357 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002358 }
2359 else if (kind == PyUnicode_2BYTE_KIND) {
2360 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002361 max_char = ucs2lib_find_max_char(u, u + len);
2362 if (max_char >= 256)
2363 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002364 }
2365 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002366 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002367 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002368 max_char = ucs4lib_find_max_char(u, u + len);
2369 if (max_char >= 0x10000)
2370 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002371 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002372 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002373 if (copy != NULL)
2374 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002375 Py_DECREF(unicode);
2376 *p_unicode = copy;
2377}
2378
Victor Stinner034f6cf2011-09-30 02:26:44 +02002379PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002380_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002381{
Victor Stinner87af4f22011-11-21 23:03:47 +01002382 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002383 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002384
Victor Stinner034f6cf2011-09-30 02:26:44 +02002385 if (!PyUnicode_Check(unicode)) {
2386 PyErr_BadInternalCall();
2387 return NULL;
2388 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002389 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002390 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002391
Victor Stinner87af4f22011-11-21 23:03:47 +01002392 length = PyUnicode_GET_LENGTH(unicode);
2393 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002394 if (!copy)
2395 return NULL;
2396 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2397
Christian Heimesf051e432016-09-13 20:22:02 +02002398 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002399 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002400 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002401 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002402}
2403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002404
Victor Stinnerbc603d12011-10-02 01:00:40 +02002405/* Widen Unicode objects to larger buffers. Don't write terminating null
2406 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407
2408void*
2409_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2410{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002411 Py_ssize_t len;
2412 void *result;
2413 unsigned int skind;
2414
Benjamin Petersonbac79492012-01-14 13:34:47 -05002415 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002416 return NULL;
2417
2418 len = PyUnicode_GET_LENGTH(s);
2419 skind = PyUnicode_KIND(s);
2420 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002421 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002422 return NULL;
2423 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002424 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002425 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002426 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002427 if (!result)
2428 return PyErr_NoMemory();
2429 assert(skind == PyUnicode_1BYTE_KIND);
2430 _PyUnicode_CONVERT_BYTES(
2431 Py_UCS1, Py_UCS2,
2432 PyUnicode_1BYTE_DATA(s),
2433 PyUnicode_1BYTE_DATA(s) + len,
2434 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002436 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002437 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002438 if (!result)
2439 return PyErr_NoMemory();
2440 if (skind == PyUnicode_2BYTE_KIND) {
2441 _PyUnicode_CONVERT_BYTES(
2442 Py_UCS2, Py_UCS4,
2443 PyUnicode_2BYTE_DATA(s),
2444 PyUnicode_2BYTE_DATA(s) + len,
2445 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002446 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002447 else {
2448 assert(skind == PyUnicode_1BYTE_KIND);
2449 _PyUnicode_CONVERT_BYTES(
2450 Py_UCS1, Py_UCS4,
2451 PyUnicode_1BYTE_DATA(s),
2452 PyUnicode_1BYTE_DATA(s) + len,
2453 result);
2454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002456 default:
2457 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002458 }
Victor Stinner01698042011-10-04 00:04:26 +02002459 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002460 return NULL;
2461}
2462
2463static Py_UCS4*
2464as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2465 int copy_null)
2466{
2467 int kind;
2468 void *data;
2469 Py_ssize_t len, targetlen;
2470 if (PyUnicode_READY(string) == -1)
2471 return NULL;
2472 kind = PyUnicode_KIND(string);
2473 data = PyUnicode_DATA(string);
2474 len = PyUnicode_GET_LENGTH(string);
2475 targetlen = len;
2476 if (copy_null)
2477 targetlen++;
2478 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002479 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002480 if (!target) {
2481 PyErr_NoMemory();
2482 return NULL;
2483 }
2484 }
2485 else {
2486 if (targetsize < targetlen) {
2487 PyErr_Format(PyExc_SystemError,
2488 "string is longer than the buffer");
2489 if (copy_null && 0 < targetsize)
2490 target[0] = 0;
2491 return NULL;
2492 }
2493 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002494 if (kind == PyUnicode_1BYTE_KIND) {
2495 Py_UCS1 *start = (Py_UCS1 *) data;
2496 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002498 else if (kind == PyUnicode_2BYTE_KIND) {
2499 Py_UCS2 *start = (Py_UCS2 *) data;
2500 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2501 }
2502 else {
2503 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002504 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002506 if (copy_null)
2507 target[len] = 0;
2508 return target;
2509}
2510
2511Py_UCS4*
2512PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2513 int copy_null)
2514{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002515 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002516 PyErr_BadInternalCall();
2517 return NULL;
2518 }
2519 return as_ucs4(string, target, targetsize, copy_null);
2520}
2521
2522Py_UCS4*
2523PyUnicode_AsUCS4Copy(PyObject *string)
2524{
2525 return as_ucs4(string, NULL, 0, 1);
2526}
2527
Victor Stinner15a11362012-10-06 23:48:20 +02002528/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002529 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2530 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2531#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002532
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002533static int
2534unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2535 Py_ssize_t width, Py_ssize_t precision)
2536{
2537 Py_ssize_t length, fill, arglen;
2538 Py_UCS4 maxchar;
2539
2540 if (PyUnicode_READY(str) == -1)
2541 return -1;
2542
2543 length = PyUnicode_GET_LENGTH(str);
2544 if ((precision == -1 || precision >= length)
2545 && width <= length)
2546 return _PyUnicodeWriter_WriteStr(writer, str);
2547
2548 if (precision != -1)
2549 length = Py_MIN(precision, length);
2550
2551 arglen = Py_MAX(length, width);
2552 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2553 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2554 else
2555 maxchar = writer->maxchar;
2556
2557 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2558 return -1;
2559
2560 if (width > length) {
2561 fill = width - length;
2562 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2563 return -1;
2564 writer->pos += fill;
2565 }
2566
2567 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2568 str, 0, length);
2569 writer->pos += length;
2570 return 0;
2571}
2572
2573static int
2574unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2575 Py_ssize_t width, Py_ssize_t precision)
2576{
2577 /* UTF-8 */
2578 Py_ssize_t length;
2579 PyObject *unicode;
2580 int res;
2581
Miss Islington (bot)cbc7c2c2019-01-12 00:52:55 -08002582 if (precision == -1) {
2583 length = strlen(str);
2584 }
2585 else {
2586 length = 0;
2587 while (length < precision && str[length]) {
2588 length++;
2589 }
2590 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002591 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2592 if (unicode == NULL)
2593 return -1;
2594
2595 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2596 Py_DECREF(unicode);
2597 return res;
2598}
2599
Victor Stinner96865452011-03-01 23:44:09 +00002600static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002601unicode_fromformat_arg(_PyUnicodeWriter *writer,
2602 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002603{
Victor Stinnere215d962012-10-06 23:03:36 +02002604 const char *p;
2605 Py_ssize_t len;
2606 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002607 Py_ssize_t width;
2608 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002609 int longflag;
2610 int longlongflag;
2611 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002612 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002613
2614 p = f;
2615 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002616 zeropad = 0;
2617 if (*f == '0') {
2618 zeropad = 1;
2619 f++;
2620 }
Victor Stinner96865452011-03-01 23:44:09 +00002621
2622 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002623 width = -1;
2624 if (Py_ISDIGIT((unsigned)*f)) {
2625 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002626 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002627 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002628 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002629 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002630 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002631 return NULL;
2632 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002633 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002634 f++;
2635 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002636 }
2637 precision = -1;
2638 if (*f == '.') {
2639 f++;
2640 if (Py_ISDIGIT((unsigned)*f)) {
2641 precision = (*f - '0');
2642 f++;
2643 while (Py_ISDIGIT((unsigned)*f)) {
2644 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2645 PyErr_SetString(PyExc_ValueError,
2646 "precision too big");
2647 return NULL;
2648 }
2649 precision = (precision * 10) + (*f - '0');
2650 f++;
2651 }
2652 }
Victor Stinner96865452011-03-01 23:44:09 +00002653 if (*f == '%') {
2654 /* "%.3%s" => f points to "3" */
2655 f--;
2656 }
2657 }
2658 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002659 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002660 f--;
2661 }
Victor Stinner96865452011-03-01 23:44:09 +00002662
2663 /* Handle %ld, %lu, %lld and %llu. */
2664 longflag = 0;
2665 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002666 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002667 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002668 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002669 longflag = 1;
2670 ++f;
2671 }
Victor Stinner96865452011-03-01 23:44:09 +00002672 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002673 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002674 longlongflag = 1;
2675 f += 2;
2676 }
Victor Stinner96865452011-03-01 23:44:09 +00002677 }
2678 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002679 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002680 size_tflag = 1;
2681 ++f;
2682 }
Victor Stinnere215d962012-10-06 23:03:36 +02002683
2684 if (f[1] == '\0')
2685 writer->overallocate = 0;
2686
2687 switch (*f) {
2688 case 'c':
2689 {
2690 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002691 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002692 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002693 "character argument not in range(0x110000)");
2694 return NULL;
2695 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002696 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002697 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002698 break;
2699 }
2700
2701 case 'i':
2702 case 'd':
2703 case 'u':
2704 case 'x':
2705 {
2706 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002707 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002708 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002709
2710 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002711 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002712 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002713 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002714 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002715 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002716 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002717 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002718 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002719 va_arg(*vargs, size_t));
2720 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002721 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002722 va_arg(*vargs, unsigned int));
2723 }
2724 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002725 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002726 }
2727 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002728 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002729 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002730 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002731 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002732 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002733 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002734 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002735 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002736 va_arg(*vargs, Py_ssize_t));
2737 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002738 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002739 va_arg(*vargs, int));
2740 }
2741 assert(len >= 0);
2742
Victor Stinnere215d962012-10-06 23:03:36 +02002743 if (precision < len)
2744 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002745
2746 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002747 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2748 return NULL;
2749
Victor Stinnere215d962012-10-06 23:03:36 +02002750 if (width > precision) {
2751 Py_UCS4 fillchar;
2752 fill = width - precision;
2753 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002754 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2755 return NULL;
2756 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002757 }
Victor Stinner15a11362012-10-06 23:48:20 +02002758 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002759 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002760 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2761 return NULL;
2762 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002763 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002764
Victor Stinner4a587072013-11-19 12:54:53 +01002765 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2766 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002767 break;
2768 }
2769
2770 case 'p':
2771 {
2772 char number[MAX_LONG_LONG_CHARS];
2773
2774 len = sprintf(number, "%p", va_arg(*vargs, void*));
2775 assert(len >= 0);
2776
2777 /* %p is ill-defined: ensure leading 0x. */
2778 if (number[1] == 'X')
2779 number[1] = 'x';
2780 else if (number[1] != 'x') {
2781 memmove(number + 2, number,
2782 strlen(number) + 1);
2783 number[0] = '0';
2784 number[1] = 'x';
2785 len += 2;
2786 }
2787
Victor Stinner4a587072013-11-19 12:54:53 +01002788 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002789 return NULL;
2790 break;
2791 }
2792
2793 case 's':
2794 {
2795 /* UTF-8 */
2796 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002797 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002798 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002799 break;
2800 }
2801
2802 case 'U':
2803 {
2804 PyObject *obj = va_arg(*vargs, PyObject *);
2805 assert(obj && _PyUnicode_CHECK(obj));
2806
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002807 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002808 return NULL;
2809 break;
2810 }
2811
2812 case 'V':
2813 {
2814 PyObject *obj = va_arg(*vargs, PyObject *);
2815 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002816 if (obj) {
2817 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002818 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002819 return NULL;
2820 }
2821 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002822 assert(str != NULL);
2823 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002824 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002825 }
2826 break;
2827 }
2828
2829 case 'S':
2830 {
2831 PyObject *obj = va_arg(*vargs, PyObject *);
2832 PyObject *str;
2833 assert(obj);
2834 str = PyObject_Str(obj);
2835 if (!str)
2836 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002837 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002838 Py_DECREF(str);
2839 return NULL;
2840 }
2841 Py_DECREF(str);
2842 break;
2843 }
2844
2845 case 'R':
2846 {
2847 PyObject *obj = va_arg(*vargs, PyObject *);
2848 PyObject *repr;
2849 assert(obj);
2850 repr = PyObject_Repr(obj);
2851 if (!repr)
2852 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002853 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002854 Py_DECREF(repr);
2855 return NULL;
2856 }
2857 Py_DECREF(repr);
2858 break;
2859 }
2860
2861 case 'A':
2862 {
2863 PyObject *obj = va_arg(*vargs, PyObject *);
2864 PyObject *ascii;
2865 assert(obj);
2866 ascii = PyObject_ASCII(obj);
2867 if (!ascii)
2868 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002869 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002870 Py_DECREF(ascii);
2871 return NULL;
2872 }
2873 Py_DECREF(ascii);
2874 break;
2875 }
2876
2877 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002878 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002879 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002880 break;
2881
2882 default:
2883 /* if we stumble upon an unknown formatting code, copy the rest
2884 of the format string to the output string. (we cannot just
2885 skip the code, since there's no way to know what's in the
2886 argument list) */
2887 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002888 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002889 return NULL;
2890 f = p+len;
2891 return f;
2892 }
2893
2894 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002895 return f;
2896}
2897
Walter Dörwaldd2034312007-05-18 16:29:38 +00002898PyObject *
2899PyUnicode_FromFormatV(const char *format, va_list vargs)
2900{
Victor Stinnere215d962012-10-06 23:03:36 +02002901 va_list vargs2;
2902 const char *f;
2903 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002904
Victor Stinner8f674cc2013-04-17 23:02:17 +02002905 _PyUnicodeWriter_Init(&writer);
2906 writer.min_length = strlen(format) + 100;
2907 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002908
Benjamin Peterson0c212142016-09-20 20:39:33 -07002909 // Copy varags to be able to pass a reference to a subfunction.
2910 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002911
2912 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002913 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002914 f = unicode_fromformat_arg(&writer, f, &vargs2);
2915 if (f == NULL)
2916 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002917 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002918 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002919 const char *p;
2920 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002921
Victor Stinnere215d962012-10-06 23:03:36 +02002922 p = f;
2923 do
2924 {
2925 if ((unsigned char)*p > 127) {
2926 PyErr_Format(PyExc_ValueError,
2927 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2928 "string, got a non-ASCII byte: 0x%02x",
2929 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002930 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002931 }
2932 p++;
2933 }
2934 while (*p != '\0' && *p != '%');
2935 len = p - f;
2936
2937 if (*p == '\0')
2938 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002939
2940 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002941 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002942
2943 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002944 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002945 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002946 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002947 return _PyUnicodeWriter_Finish(&writer);
2948
2949 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002950 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002951 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002952 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002953}
2954
Walter Dörwaldd2034312007-05-18 16:29:38 +00002955PyObject *
2956PyUnicode_FromFormat(const char *format, ...)
2957{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002958 PyObject* ret;
2959 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002960
2961#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002962 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002963#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002964 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002965#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002966 ret = PyUnicode_FromFormatV(format, vargs);
2967 va_end(vargs);
2968 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002969}
2970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971#ifdef HAVE_WCHAR_H
2972
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002973/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00002974
Victor Stinnerd88d9832011-09-06 02:00:05 +02002975 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002976 character) required to convert the unicode object. Ignore size argument.
2977
Victor Stinnerd88d9832011-09-06 02:00:05 +02002978 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002979 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002980 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002981Py_ssize_t
2982PyUnicode_AsWideChar(PyObject *unicode,
2983 wchar_t *w,
2984 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00002985{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002986 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002987 const wchar_t *wstr;
2988
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002989 if (unicode == NULL) {
2990 PyErr_BadInternalCall();
2991 return -1;
2992 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002993 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002994 if (wstr == NULL)
2995 return -1;
2996
Victor Stinner5593d8a2010-10-02 11:11:27 +00002997 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002998 if (size > res)
2999 size = res + 1;
3000 else
3001 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02003002 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003003 return res;
3004 }
3005 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003006 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00003007}
3008
Victor Stinner137c34c2010-09-29 10:25:54 +00003009wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003010PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003011 Py_ssize_t *size)
3012{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003013 const wchar_t *wstr;
3014 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003015 Py_ssize_t buflen;
3016
3017 if (unicode == NULL) {
3018 PyErr_BadInternalCall();
3019 return NULL;
3020 }
3021
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003022 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
3023 if (wstr == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003024 return NULL;
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003025 }
3026 if (size == NULL && wcslen(wstr) != (size_t)buflen) {
3027 PyErr_SetString(PyExc_ValueError,
3028 "embedded null character");
3029 return NULL;
3030 }
3031
3032 buffer = PyMem_NEW(wchar_t, buflen + 1);
Victor Stinner137c34c2010-09-29 10:25:54 +00003033 if (buffer == NULL) {
3034 PyErr_NoMemory();
3035 return NULL;
3036 }
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003037 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003038 if (size != NULL)
3039 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003040 return buffer;
3041}
3042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003043#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003044
Alexander Belopolsky40018472011-02-26 01:02:56 +00003045PyObject *
3046PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003047{
Victor Stinner8faf8212011-12-08 22:14:11 +01003048 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003049 PyErr_SetString(PyExc_ValueError,
3050 "chr() arg not in range(0x110000)");
3051 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003052 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003053
Victor Stinner985a82a2014-01-03 12:53:47 +01003054 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003055}
3056
Alexander Belopolsky40018472011-02-26 01:02:56 +00003057PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003058PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003059{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003060 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003061 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003062 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003063 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003064 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003065 Py_INCREF(obj);
3066 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003067 }
3068 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003069 /* For a Unicode subtype that's not a Unicode object,
3070 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003071 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003073 PyErr_Format(PyExc_TypeError,
3074 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003075 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003076 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003077}
3078
Alexander Belopolsky40018472011-02-26 01:02:56 +00003079PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003080PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003081 const char *encoding,
3082 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003083{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003084 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003085 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003086
Guido van Rossumd57fd912000-03-10 22:53:23 +00003087 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003088 PyErr_BadInternalCall();
3089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003091
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003092 /* Decoding bytes objects is the most common case and should be fast */
3093 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003094 if (PyBytes_GET_SIZE(obj) == 0)
3095 _Py_RETURN_UNICODE_EMPTY();
3096 v = PyUnicode_Decode(
3097 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3098 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003099 return v;
3100 }
3101
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003102 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003103 PyErr_SetString(PyExc_TypeError,
3104 "decoding str is not supported");
3105 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003106 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003107
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003108 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3109 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3110 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003111 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003112 Py_TYPE(obj)->tp_name);
3113 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003114 }
Tim Petersced69f82003-09-16 20:30:58 +00003115
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003116 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003117 PyBuffer_Release(&buffer);
3118 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003119 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003120
Serhiy Storchaka05997252013-01-26 12:14:02 +02003121 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003122 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003123 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003124}
3125
Victor Stinnerebe17e02016-10-12 13:57:45 +02003126/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3127 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3128 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003129int
3130_Py_normalize_encoding(const char *encoding,
3131 char *lower,
3132 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003133{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003134 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003135 char *l;
3136 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003137 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003138
Victor Stinner942889a2016-09-05 15:40:10 -07003139 assert(encoding != NULL);
3140
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003141 e = encoding;
3142 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003143 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003144 punct = 0;
3145 while (1) {
3146 char c = *e;
3147 if (c == 0) {
3148 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003149 }
Victor Stinner942889a2016-09-05 15:40:10 -07003150
3151 if (Py_ISALNUM(c) || c == '.') {
3152 if (punct && l != lower) {
3153 if (l == l_end) {
3154 return 0;
3155 }
3156 *l++ = '_';
3157 }
3158 punct = 0;
3159
3160 if (l == l_end) {
3161 return 0;
3162 }
3163 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003164 }
3165 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003166 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003167 }
Victor Stinner942889a2016-09-05 15:40:10 -07003168
3169 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003170 }
3171 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003172 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003173}
3174
Alexander Belopolsky40018472011-02-26 01:02:56 +00003175PyObject *
3176PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003177 Py_ssize_t size,
3178 const char *encoding,
3179 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003180{
3181 PyObject *buffer = NULL, *unicode;
3182 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003183 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3184
3185 if (encoding == NULL) {
3186 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3187 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003188
Fred Drakee4315f52000-05-09 19:53:39 +00003189 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003190 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3191 char *lower = buflower;
3192
3193 /* Fast paths */
3194 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3195 lower += 3;
3196 if (*lower == '_') {
3197 /* Match "utf8" and "utf_8" */
3198 lower++;
3199 }
3200
3201 if (lower[0] == '8' && lower[1] == 0) {
3202 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3203 }
3204 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3205 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3206 }
3207 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3208 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3209 }
3210 }
3211 else {
3212 if (strcmp(lower, "ascii") == 0
3213 || strcmp(lower, "us_ascii") == 0) {
3214 return PyUnicode_DecodeASCII(s, size, errors);
3215 }
Steve Dowercc16be82016-09-08 10:35:16 -07003216 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003217 else if (strcmp(lower, "mbcs") == 0) {
3218 return PyUnicode_DecodeMBCS(s, size, errors);
3219 }
3220 #endif
3221 else if (strcmp(lower, "latin1") == 0
3222 || strcmp(lower, "latin_1") == 0
3223 || strcmp(lower, "iso_8859_1") == 0
3224 || strcmp(lower, "iso8859_1") == 0) {
3225 return PyUnicode_DecodeLatin1(s, size, errors);
3226 }
3227 }
Victor Stinner37296e82010-06-10 13:36:23 +00003228 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003229
3230 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003231 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003232 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003233 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003234 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003235 if (buffer == NULL)
3236 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003237 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003238 if (unicode == NULL)
3239 goto onError;
3240 if (!PyUnicode_Check(unicode)) {
3241 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003242 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3243 "use codecs.decode() to decode to arbitrary types",
3244 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003245 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003246 Py_DECREF(unicode);
3247 goto onError;
3248 }
3249 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003250 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003251
Benjamin Peterson29060642009-01-31 22:14:21 +00003252 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003253 Py_XDECREF(buffer);
3254 return NULL;
3255}
3256
Alexander Belopolsky40018472011-02-26 01:02:56 +00003257PyObject *
3258PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003259 const char *encoding,
3260 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003261{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003262 if (!PyUnicode_Check(unicode)) {
3263 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003264 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003265 }
3266
Serhiy Storchaka00939072016-10-27 21:05:49 +03003267 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3268 "PyUnicode_AsDecodedObject() is deprecated; "
3269 "use PyCodec_Decode() to decode from str", 1) < 0)
3270 return NULL;
3271
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003272 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003273 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003274
3275 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003276 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003277}
3278
Alexander Belopolsky40018472011-02-26 01:02:56 +00003279PyObject *
3280PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003281 const char *encoding,
3282 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003283{
3284 PyObject *v;
3285
3286 if (!PyUnicode_Check(unicode)) {
3287 PyErr_BadArgument();
3288 goto onError;
3289 }
3290
Serhiy Storchaka00939072016-10-27 21:05:49 +03003291 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3292 "PyUnicode_AsDecodedUnicode() is deprecated; "
3293 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3294 return NULL;
3295
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003296 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003297 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003298
3299 /* Decode via the codec registry */
3300 v = PyCodec_Decode(unicode, encoding, errors);
3301 if (v == NULL)
3302 goto onError;
3303 if (!PyUnicode_Check(v)) {
3304 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003305 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3306 "use codecs.decode() to decode to arbitrary types",
3307 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003308 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003309 Py_DECREF(v);
3310 goto onError;
3311 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003312 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003313
Benjamin Peterson29060642009-01-31 22:14:21 +00003314 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003315 return NULL;
3316}
3317
Alexander Belopolsky40018472011-02-26 01:02:56 +00003318PyObject *
3319PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003320 Py_ssize_t size,
3321 const char *encoding,
3322 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003323{
3324 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003325
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003326 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003327 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003328 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003329 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3330 Py_DECREF(unicode);
3331 return v;
3332}
3333
Alexander Belopolsky40018472011-02-26 01:02:56 +00003334PyObject *
3335PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003336 const char *encoding,
3337 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003338{
3339 PyObject *v;
3340
3341 if (!PyUnicode_Check(unicode)) {
3342 PyErr_BadArgument();
3343 goto onError;
3344 }
3345
Serhiy Storchaka00939072016-10-27 21:05:49 +03003346 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3347 "PyUnicode_AsEncodedObject() is deprecated; "
3348 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3349 "or PyCodec_Encode() for generic encoding", 1) < 0)
3350 return NULL;
3351
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003352 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003353 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003354
3355 /* Encode via the codec registry */
3356 v = PyCodec_Encode(unicode, encoding, errors);
3357 if (v == NULL)
3358 goto onError;
3359 return v;
3360
Benjamin Peterson29060642009-01-31 22:14:21 +00003361 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003362 return NULL;
3363}
3364
Victor Stinner1b579672011-12-17 05:47:23 +01003365static int
3366locale_error_handler(const char *errors, int *surrogateescape)
3367{
Victor Stinner50149202015-09-22 00:26:54 +02003368 _Py_error_handler error_handler = get_error_handler(errors);
3369 switch (error_handler)
3370 {
3371 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003372 *surrogateescape = 0;
3373 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003374 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003375 *surrogateescape = 1;
3376 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003377 default:
3378 PyErr_Format(PyExc_ValueError,
3379 "only 'strict' and 'surrogateescape' error handlers "
3380 "are supported, not '%s'",
3381 errors);
3382 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003383 }
Victor Stinner1b579672011-12-17 05:47:23 +01003384}
3385
Victor Stinner2cba6b82018-01-10 22:46:15 +01003386static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003387unicode_encode_locale(PyObject *unicode, const char *errors,
3388 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003389{
Victor Stinner1b579672011-12-17 05:47:23 +01003390 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003391 if (locale_error_handler(errors, &surrogateescape) < 0)
3392 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003393
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003394 Py_ssize_t wlen;
3395 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3396 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003397 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003398 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003399
Victor Stinner85ab9742018-11-28 12:42:40 +01003400 if ((size_t)wlen != wcslen(wstr)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003401 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner85ab9742018-11-28 12:42:40 +01003402 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003403 return NULL;
3404 }
3405
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003406 char *str;
3407 size_t error_pos;
3408 const char *reason;
3409 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
3410 current_locale, surrogateescape);
Victor Stinner85ab9742018-11-28 12:42:40 +01003411 PyMem_Free(wstr);
3412
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003413 if (res != 0) {
3414 if (res == -2) {
3415 PyObject *exc;
3416 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3417 "locale", unicode,
3418 (Py_ssize_t)error_pos,
3419 (Py_ssize_t)(error_pos+1),
3420 reason);
3421 if (exc != NULL) {
3422 PyCodec_StrictErrors(exc);
3423 Py_DECREF(exc);
3424 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003425 }
3426 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003427 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003428 }
Victor Stinner85ab9742018-11-28 12:42:40 +01003429 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003430 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003431
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003432 PyObject *bytes = PyBytes_FromString(str);
3433 PyMem_RawFree(str);
3434 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003435}
3436
Victor Stinnerad158722010-10-27 00:25:46 +00003437PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003438PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3439{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003440 return unicode_encode_locale(unicode, errors, 1);
3441}
3442
3443PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003444PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003445{
Steve Dowercc16be82016-09-08 10:35:16 -07003446#if defined(__APPLE__)
3447 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003448#else
Victor Stinner793b5312011-04-27 00:24:21 +02003449 PyInterpreterState *interp = PyThreadState_GET()->interp;
3450 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3451 cannot use it to encode and decode filenames before it is loaded. Load
3452 the Python codec requires to encode at least its own filename. Use the C
3453 version of the locale codec until the codec registry is initialized and
3454 the Python codec is loaded.
3455
3456 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3457 cannot only rely on it: check also interp->fscodec_initialized for
3458 subinterpreters. */
3459 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003460 return PyUnicode_AsEncodedString(unicode,
3461 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003462 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003463 }
3464 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003465 return unicode_encode_locale(unicode,
3466 Py_FileSystemDefaultEncodeErrors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003467 }
Victor Stinnerad158722010-10-27 00:25:46 +00003468#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003469}
3470
Alexander Belopolsky40018472011-02-26 01:02:56 +00003471PyObject *
3472PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003473 const char *encoding,
3474 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003475{
3476 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003477 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003478
Guido van Rossumd57fd912000-03-10 22:53:23 +00003479 if (!PyUnicode_Check(unicode)) {
3480 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003481 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003482 }
Fred Drakee4315f52000-05-09 19:53:39 +00003483
Victor Stinner942889a2016-09-05 15:40:10 -07003484 if (encoding == NULL) {
3485 return _PyUnicode_AsUTF8String(unicode, errors);
3486 }
3487
Fred Drakee4315f52000-05-09 19:53:39 +00003488 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003489 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3490 char *lower = buflower;
3491
3492 /* Fast paths */
3493 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3494 lower += 3;
3495 if (*lower == '_') {
3496 /* Match "utf8" and "utf_8" */
3497 lower++;
3498 }
3499
3500 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003501 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003502 }
3503 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3504 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3505 }
3506 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3507 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3508 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003509 }
Victor Stinner942889a2016-09-05 15:40:10 -07003510 else {
3511 if (strcmp(lower, "ascii") == 0
3512 || strcmp(lower, "us_ascii") == 0) {
3513 return _PyUnicode_AsASCIIString(unicode, errors);
3514 }
Steve Dowercc16be82016-09-08 10:35:16 -07003515#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003516 else if (strcmp(lower, "mbcs") == 0) {
3517 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3518 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003519#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003520 else if (strcmp(lower, "latin1") == 0 ||
3521 strcmp(lower, "latin_1") == 0 ||
3522 strcmp(lower, "iso_8859_1") == 0 ||
3523 strcmp(lower, "iso8859_1") == 0) {
3524 return _PyUnicode_AsLatin1String(unicode, errors);
3525 }
3526 }
Victor Stinner37296e82010-06-10 13:36:23 +00003527 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528
3529 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003530 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003531 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003532 return NULL;
3533
3534 /* The normal path */
3535 if (PyBytes_Check(v))
3536 return v;
3537
3538 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003539 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003540 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003541 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003542
3543 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003544 "encoder %s returned bytearray instead of bytes; "
3545 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003546 encoding);
3547 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003548 Py_DECREF(v);
3549 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003550 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003551
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003552 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3553 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003554 Py_DECREF(v);
3555 return b;
3556 }
3557
3558 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003559 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3560 "use codecs.encode() to encode to arbitrary types",
3561 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003562 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003563 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003564 return NULL;
3565}
3566
Alexander Belopolsky40018472011-02-26 01:02:56 +00003567PyObject *
3568PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003569 const char *encoding,
3570 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003571{
3572 PyObject *v;
3573
3574 if (!PyUnicode_Check(unicode)) {
3575 PyErr_BadArgument();
3576 goto onError;
3577 }
3578
Serhiy Storchaka00939072016-10-27 21:05:49 +03003579 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3580 "PyUnicode_AsEncodedUnicode() is deprecated; "
3581 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3582 return NULL;
3583
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003584 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003585 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003586
3587 /* Encode via the codec registry */
3588 v = PyCodec_Encode(unicode, encoding, errors);
3589 if (v == NULL)
3590 goto onError;
3591 if (!PyUnicode_Check(v)) {
3592 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003593 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3594 "use codecs.encode() to encode to arbitrary types",
3595 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003596 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003597 Py_DECREF(v);
3598 goto onError;
3599 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003600 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003601
Benjamin Peterson29060642009-01-31 22:14:21 +00003602 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003603 return NULL;
3604}
3605
Victor Stinner2cba6b82018-01-10 22:46:15 +01003606static PyObject*
3607unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3608 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003609{
Victor Stinner1b579672011-12-17 05:47:23 +01003610 int surrogateescape;
Victor Stinner1b579672011-12-17 05:47:23 +01003611 if (locale_error_handler(errors, &surrogateescape) < 0)
3612 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003613
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003614 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3615 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003616 return NULL;
3617 }
3618
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003619 wchar_t *wstr;
3620 size_t wlen;
3621 const char *reason;
3622 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
3623 current_locale, surrogateescape);
3624 if (res != 0) {
3625 if (res == -2) {
3626 PyObject *exc;
3627 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3628 "locale", str, len,
3629 (Py_ssize_t)wlen,
3630 (Py_ssize_t)(wlen + 1),
3631 reason);
3632 if (exc != NULL) {
3633 PyCodec_StrictErrors(exc);
3634 Py_DECREF(exc);
3635 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003636 }
3637 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003638 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003639 }
Victor Stinner2f197072011-12-17 07:08:30 +01003640 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003641 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003642
3643 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3644 PyMem_RawFree(wstr);
3645 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003646}
3647
3648PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003649PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3650 const char *errors)
3651{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003652 return unicode_decode_locale(str, len, errors, 1);
3653}
3654
3655PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003656PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003657{
3658 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003659 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003660}
3661
3662
3663PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003664PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003665 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003666 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3667}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003668
Christian Heimes5894ba72007-11-04 11:43:14 +00003669PyObject*
3670PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3671{
Steve Dowercc16be82016-09-08 10:35:16 -07003672#if defined(__APPLE__)
3673 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003674#else
Victor Stinner793b5312011-04-27 00:24:21 +02003675 PyInterpreterState *interp = PyThreadState_GET()->interp;
3676 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3677 cannot use it to encode and decode filenames before it is loaded. Load
3678 the Python codec requires to encode at least its own filename. Use the C
3679 version of the locale codec until the codec registry is initialized and
3680 the Python codec is loaded.
3681
3682 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3683 cannot only rely on it: check also interp->fscodec_initialized for
3684 subinterpreters. */
3685 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003686 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003687 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003688 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003689 }
3690 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003691 return unicode_decode_locale(s, size,
3692 Py_FileSystemDefaultEncodeErrors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003693 }
Victor Stinnerad158722010-10-27 00:25:46 +00003694#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003695}
3696
Martin v. Löwis011e8422009-05-05 04:43:17 +00003697
3698int
3699PyUnicode_FSConverter(PyObject* arg, void* addr)
3700{
Brett Cannonec6ce872016-09-06 15:50:29 -07003701 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003702 PyObject *output = NULL;
3703 Py_ssize_t size;
3704 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003705 if (arg == NULL) {
3706 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003707 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003708 return 1;
3709 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003710 path = PyOS_FSPath(arg);
3711 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003712 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003713 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003714 if (PyBytes_Check(path)) {
3715 output = path;
3716 }
3717 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3718 output = PyUnicode_EncodeFSDefault(path);
3719 Py_DECREF(path);
3720 if (!output) {
3721 return 0;
3722 }
3723 assert(PyBytes_Check(output));
3724 }
3725
Victor Stinner0ea2a462010-04-30 00:22:08 +00003726 size = PyBytes_GET_SIZE(output);
3727 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003728 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003729 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003730 Py_DECREF(output);
3731 return 0;
3732 }
3733 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003734 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003735}
3736
3737
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003738int
3739PyUnicode_FSDecoder(PyObject* arg, void* addr)
3740{
Brett Cannona5711202016-09-06 19:36:01 -07003741 int is_buffer = 0;
3742 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003743 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003744 if (arg == NULL) {
3745 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003746 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003747 return 1;
3748 }
Brett Cannona5711202016-09-06 19:36:01 -07003749
3750 is_buffer = PyObject_CheckBuffer(arg);
3751 if (!is_buffer) {
3752 path = PyOS_FSPath(arg);
3753 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003754 return 0;
3755 }
Brett Cannona5711202016-09-06 19:36:01 -07003756 }
3757 else {
3758 path = arg;
3759 Py_INCREF(arg);
3760 }
3761
3762 if (PyUnicode_Check(path)) {
3763 if (PyUnicode_READY(path) == -1) {
3764 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003765 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003766 }
3767 output = path;
3768 }
3769 else if (PyBytes_Check(path) || is_buffer) {
3770 PyObject *path_bytes = NULL;
3771
3772 if (!PyBytes_Check(path) &&
3773 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3774 "path should be string, bytes, or os.PathLike, not %.200s",
3775 Py_TYPE(arg)->tp_name)) {
3776 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003777 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003778 }
3779 path_bytes = PyBytes_FromObject(path);
3780 Py_DECREF(path);
3781 if (!path_bytes) {
3782 return 0;
3783 }
3784 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3785 PyBytes_GET_SIZE(path_bytes));
3786 Py_DECREF(path_bytes);
3787 if (!output) {
3788 return 0;
3789 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003790 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003791 else {
3792 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003793 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003794 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003795 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003796 return 0;
3797 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003798 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003799 Py_DECREF(output);
3800 return 0;
3801 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003802 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003803 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003804 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003805 Py_DECREF(output);
3806 return 0;
3807 }
3808 *(PyObject**)addr = output;
3809 return Py_CLEANUP_SUPPORTED;
3810}
3811
3812
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003813const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003814PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003815{
Christian Heimesf3863112007-11-22 07:46:41 +00003816 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003818 if (!PyUnicode_Check(unicode)) {
3819 PyErr_BadArgument();
3820 return NULL;
3821 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003822 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003823 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003824
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003825 if (PyUnicode_UTF8(unicode) == NULL) {
3826 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003827 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003828 if (bytes == NULL)
3829 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003830 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3831 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003832 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833 Py_DECREF(bytes);
3834 return NULL;
3835 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003836 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003837 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003838 PyBytes_AS_STRING(bytes),
3839 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003840 Py_DECREF(bytes);
3841 }
3842
3843 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003844 *psize = PyUnicode_UTF8_LENGTH(unicode);
3845 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003846}
3847
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003848const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003851 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3852}
3853
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854Py_UNICODE *
3855PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3856{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003857 const unsigned char *one_byte;
3858#if SIZEOF_WCHAR_T == 4
3859 const Py_UCS2 *two_bytes;
3860#else
3861 const Py_UCS4 *four_bytes;
3862 const Py_UCS4 *ucs4_end;
3863 Py_ssize_t num_surrogates;
3864#endif
3865 wchar_t *w;
3866 wchar_t *wchar_end;
3867
3868 if (!PyUnicode_Check(unicode)) {
3869 PyErr_BadArgument();
3870 return NULL;
3871 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003872 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003873 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003874 assert(_PyUnicode_KIND(unicode) != 0);
3875 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003876
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003879 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3880 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881 num_surrogates = 0;
3882
3883 for (; four_bytes < ucs4_end; ++four_bytes) {
3884 if (*four_bytes > 0xFFFF)
3885 ++num_surrogates;
3886 }
3887
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3889 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3890 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003891 PyErr_NoMemory();
3892 return NULL;
3893 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003894 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003895
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003896 w = _PyUnicode_WSTR(unicode);
3897 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3898 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3900 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003901 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003903 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3904 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003905 }
3906 else
3907 *w = *four_bytes;
3908
3909 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07003910 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911 }
3912 }
3913 *w = 0;
3914#else
3915 /* sizeof(wchar_t) == 4 */
3916 Py_FatalError("Impossible unicode object state, wstr and str "
3917 "should share memory already.");
3918 return NULL;
3919#endif
3920 }
3921 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003922 if ((size_t)_PyUnicode_LENGTH(unicode) >
3923 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3924 PyErr_NoMemory();
3925 return NULL;
3926 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003927 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3928 (_PyUnicode_LENGTH(unicode) + 1));
3929 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 PyErr_NoMemory();
3931 return NULL;
3932 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003933 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3934 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3935 w = _PyUnicode_WSTR(unicode);
3936 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003938 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3939 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940 for (; w < wchar_end; ++one_byte, ++w)
3941 *w = *one_byte;
3942 /* null-terminate the wstr */
3943 *w = 0;
3944 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003945 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003947 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948 for (; w < wchar_end; ++two_bytes, ++w)
3949 *w = *two_bytes;
3950 /* null-terminate the wstr */
3951 *w = 0;
3952#else
3953 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003954 PyObject_FREE(_PyUnicode_WSTR(unicode));
3955 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003956 Py_FatalError("Impossible unicode object state, wstr "
3957 "and str should share memory already.");
3958 return NULL;
3959#endif
3960 }
3961 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07003962 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003963 }
3964 }
3965 }
3966 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003967 *size = PyUnicode_WSTR_LENGTH(unicode);
3968 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003969}
3970
Alexander Belopolsky40018472011-02-26 01:02:56 +00003971Py_UNICODE *
3972PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003973{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003975}
3976
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003977const Py_UNICODE *
3978_PyUnicode_AsUnicode(PyObject *unicode)
3979{
3980 Py_ssize_t size;
3981 const Py_UNICODE *wstr;
3982
3983 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3984 if (wstr && wcslen(wstr) != (size_t)size) {
3985 PyErr_SetString(PyExc_ValueError, "embedded null character");
3986 return NULL;
3987 }
3988 return wstr;
3989}
3990
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003991
Alexander Belopolsky40018472011-02-26 01:02:56 +00003992Py_ssize_t
3993PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003994{
3995 if (!PyUnicode_Check(unicode)) {
3996 PyErr_BadArgument();
3997 goto onError;
3998 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003999 if (_PyUnicode_WSTR(unicode) == NULL) {
4000 if (PyUnicode_AsUnicode(unicode) == NULL)
4001 goto onError;
4002 }
4003 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004004
Benjamin Peterson29060642009-01-31 22:14:21 +00004005 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004006 return -1;
4007}
4008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004009Py_ssize_t
4010PyUnicode_GetLength(PyObject *unicode)
4011{
Victor Stinner07621332012-06-16 04:53:46 +02004012 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004013 PyErr_BadArgument();
4014 return -1;
4015 }
Victor Stinner07621332012-06-16 04:53:46 +02004016 if (PyUnicode_READY(unicode) == -1)
4017 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004018 return PyUnicode_GET_LENGTH(unicode);
4019}
4020
4021Py_UCS4
4022PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4023{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004024 void *data;
4025 int kind;
4026
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004027 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004028 PyErr_BadArgument();
4029 return (Py_UCS4)-1;
4030 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004031 if (PyUnicode_READY(unicode) == -1) {
4032 return (Py_UCS4)-1;
4033 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004034 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004035 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036 return (Py_UCS4)-1;
4037 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004038 data = PyUnicode_DATA(unicode);
4039 kind = PyUnicode_KIND(unicode);
4040 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041}
4042
4043int
4044PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4045{
4046 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004047 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004048 return -1;
4049 }
Victor Stinner488fa492011-12-12 00:01:39 +01004050 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004051 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004052 PyErr_SetString(PyExc_IndexError, "string index out of range");
4053 return -1;
4054 }
Victor Stinner488fa492011-12-12 00:01:39 +01004055 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004056 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004057 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4058 PyErr_SetString(PyExc_ValueError, "character out of range");
4059 return -1;
4060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004061 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4062 index, ch);
4063 return 0;
4064}
4065
Alexander Belopolsky40018472011-02-26 01:02:56 +00004066const char *
4067PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004068{
Victor Stinner42cb4622010-09-01 19:39:01 +00004069 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004070}
4071
Victor Stinner554f3f02010-06-16 23:33:54 +00004072/* create or adjust a UnicodeDecodeError */
4073static void
4074make_decode_exception(PyObject **exceptionObject,
4075 const char *encoding,
4076 const char *input, Py_ssize_t length,
4077 Py_ssize_t startpos, Py_ssize_t endpos,
4078 const char *reason)
4079{
4080 if (*exceptionObject == NULL) {
4081 *exceptionObject = PyUnicodeDecodeError_Create(
4082 encoding, input, length, startpos, endpos, reason);
4083 }
4084 else {
4085 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4086 goto onError;
4087 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4088 goto onError;
4089 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4090 goto onError;
4091 }
4092 return;
4093
4094onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004095 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004096}
4097
Steve Dowercc16be82016-09-08 10:35:16 -07004098#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099/* error handling callback helper:
4100 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004101 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102 and adjust various state variables.
4103 return 0 on success, -1 on error
4104*/
4105
Alexander Belopolsky40018472011-02-26 01:02:56 +00004106static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004107unicode_decode_call_errorhandler_wchar(
4108 const char *errors, PyObject **errorHandler,
4109 const char *encoding, const char *reason,
4110 const char **input, const char **inend, Py_ssize_t *startinpos,
4111 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4112 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004113{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004114 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004115
4116 PyObject *restuple = NULL;
4117 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004118 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004119 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004120 Py_ssize_t requiredsize;
4121 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004122 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004123 wchar_t *repwstr;
4124 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004125
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004126 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4127 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004128
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004129 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004130 *errorHandler = PyCodec_LookupError(errors);
4131 if (*errorHandler == NULL)
4132 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004133 }
4134
Victor Stinner554f3f02010-06-16 23:33:54 +00004135 make_decode_exception(exceptionObject,
4136 encoding,
4137 *input, *inend - *input,
4138 *startinpos, *endinpos,
4139 reason);
4140 if (*exceptionObject == NULL)
4141 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004142
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004143 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004144 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004145 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004146 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004147 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004148 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004149 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004150 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004151 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004152
4153 /* Copy back the bytes variables, which might have been modified by the
4154 callback */
4155 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4156 if (!inputobj)
4157 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004158 *input = PyBytes_AS_STRING(inputobj);
4159 insize = PyBytes_GET_SIZE(inputobj);
4160 *inend = *input + insize;
4161 /* we can DECREF safely, as the exception has another reference,
4162 so the object won't go away. */
4163 Py_DECREF(inputobj);
4164
4165 if (newpos<0)
4166 newpos = insize+newpos;
4167 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004168 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004169 goto onError;
4170 }
4171
4172 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4173 if (repwstr == NULL)
4174 goto onError;
4175 /* need more space? (at least enough for what we
4176 have+the replacement+the rest of the string (starting
4177 at the new input position), so we won't have to check space
4178 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004179 requiredsize = *outpos;
4180 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4181 goto overflow;
4182 requiredsize += repwlen;
4183 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4184 goto overflow;
4185 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004186 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004187 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188 requiredsize = 2*outsize;
4189 if (unicode_resize(output, requiredsize) < 0)
4190 goto onError;
4191 }
4192 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4193 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004194 *endinpos = newpos;
4195 *inptr = *input + newpos;
4196
4197 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004198 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004199 return 0;
4200
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004201 overflow:
4202 PyErr_SetString(PyExc_OverflowError,
4203 "decoded result is too long for a Python string");
4204
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004205 onError:
4206 Py_XDECREF(restuple);
4207 return -1;
4208}
Steve Dowercc16be82016-09-08 10:35:16 -07004209#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004210
4211static int
4212unicode_decode_call_errorhandler_writer(
4213 const char *errors, PyObject **errorHandler,
4214 const char *encoding, const char *reason,
4215 const char **input, const char **inend, Py_ssize_t *startinpos,
4216 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4217 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4218{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004219 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004220
4221 PyObject *restuple = NULL;
4222 PyObject *repunicode = NULL;
4223 Py_ssize_t insize;
4224 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004225 Py_ssize_t replen;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004226 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004227 PyObject *inputobj = NULL;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004228 int need_to_grow = 0;
4229 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004230
4231 if (*errorHandler == NULL) {
4232 *errorHandler = PyCodec_LookupError(errors);
4233 if (*errorHandler == NULL)
4234 goto onError;
4235 }
4236
4237 make_decode_exception(exceptionObject,
4238 encoding,
4239 *input, *inend - *input,
4240 *startinpos, *endinpos,
4241 reason);
4242 if (*exceptionObject == NULL)
4243 goto onError;
4244
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004245 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004246 if (restuple == NULL)
4247 goto onError;
4248 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004249 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004250 goto onError;
4251 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004252 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004253 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004254
4255 /* Copy back the bytes variables, which might have been modified by the
4256 callback */
4257 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4258 if (!inputobj)
4259 goto onError;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004260 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004261 *input = PyBytes_AS_STRING(inputobj);
4262 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004263 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004264 /* we can DECREF safely, as the exception has another reference,
4265 so the object won't go away. */
4266 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004267
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004269 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004270 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004271 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004272 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004273 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004274
Victor Stinner170ca6f2013-04-18 00:25:28 +02004275 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004276 if (replen > 1) {
4277 writer->min_length += replen - 1;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004278 need_to_grow = 1;
4279 }
4280 new_inptr = *input + newpos;
4281 if (*inend - new_inptr > remain) {
4282 /* We don't know the decoding algorithm here so we make the worst
4283 assumption that one byte decodes to one unicode character.
4284 If unfortunately one byte could decode to more unicode characters,
4285 the decoder may write out-of-bound then. Is it possible for the
4286 algorithms using this function? */
4287 writer->min_length += *inend - new_inptr - remain;
4288 need_to_grow = 1;
4289 }
4290 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004291 writer->overallocate = 1;
Miss Islington (bot)09819ef2018-02-12 23:15:57 -08004292 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004293 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4294 goto onError;
4295 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004296 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004297 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004298
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004299 *endinpos = newpos;
Xiang Zhang86fdad02018-01-31 20:48:05 +08004300 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004301
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004302 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004303 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004304 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004305
Benjamin Peterson29060642009-01-31 22:14:21 +00004306 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004307 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004308 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004309}
4310
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004311/* --- UTF-7 Codec -------------------------------------------------------- */
4312
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313/* See RFC2152 for details. We encode conservatively and decode liberally. */
4314
4315/* Three simple macros defining base-64. */
4316
4317/* Is c a base-64 character? */
4318
4319#define IS_BASE64(c) \
4320 (((c) >= 'A' && (c) <= 'Z') || \
4321 ((c) >= 'a' && (c) <= 'z') || \
4322 ((c) >= '0' && (c) <= '9') || \
4323 (c) == '+' || (c) == '/')
4324
4325/* given that c is a base-64 character, what is its base-64 value? */
4326
4327#define FROM_BASE64(c) \
4328 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4329 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4330 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4331 (c) == '+' ? 62 : 63)
4332
4333/* What is the base-64 character of the bottom 6 bits of n? */
4334
4335#define TO_BASE64(n) \
4336 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4337
4338/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4339 * decoded as itself. We are permissive on decoding; the only ASCII
4340 * byte not decoding to itself is the + which begins a base64
4341 * string. */
4342
4343#define DECODE_DIRECT(c) \
4344 ((c) <= 127 && (c) != '+')
4345
4346/* The UTF-7 encoder treats ASCII characters differently according to
4347 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4348 * the above). See RFC2152. This array identifies these different
4349 * sets:
4350 * 0 : "Set D"
4351 * alphanumeric and '(),-./:?
4352 * 1 : "Set O"
4353 * !"#$%&*;<=>@[]^_`{|}
4354 * 2 : "whitespace"
4355 * ht nl cr sp
4356 * 3 : special (must be base64 encoded)
4357 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4358 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359
Tim Petersced69f82003-09-16 20:30:58 +00004360static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361char utf7_category[128] = {
4362/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4363 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4364/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4365 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4366/* sp ! " # $ % & ' ( ) * + , - . / */
4367 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4368/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4369 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4370/* @ A B C D E F G H I J K L M N O */
4371 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4372/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4373 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4374/* ` a b c d e f g h i j k l m n o */
4375 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4376/* p q r s t u v w x y z { | } ~ del */
4377 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378};
4379
Antoine Pitrou244651a2009-05-04 18:56:13 +00004380/* ENCODE_DIRECT: this character should be encoded as itself. The
4381 * answer depends on whether we are encoding set O as itself, and also
4382 * on whether we are encoding whitespace as itself. RFC2152 makes it
4383 * clear that the answers to these questions vary between
4384 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004385
Antoine Pitrou244651a2009-05-04 18:56:13 +00004386#define ENCODE_DIRECT(c, directO, directWS) \
4387 ((c) < 128 && (c) > 0 && \
4388 ((utf7_category[(c)] == 0) || \
4389 (directWS && (utf7_category[(c)] == 2)) || \
4390 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004391
Alexander Belopolsky40018472011-02-26 01:02:56 +00004392PyObject *
4393PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004394 Py_ssize_t size,
4395 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004397 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4398}
4399
Antoine Pitrou244651a2009-05-04 18:56:13 +00004400/* The decoder. The only state we preserve is our read position,
4401 * i.e. how many characters we have consumed. So if we end in the
4402 * middle of a shift sequence we have to back off the read position
4403 * and the output to the beginning of the sequence, otherwise we lose
4404 * all the shift state (seen bits, number of bits seen, high
4405 * surrogate). */
4406
Alexander Belopolsky40018472011-02-26 01:02:56 +00004407PyObject *
4408PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004409 Py_ssize_t size,
4410 const char *errors,
4411 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004412{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004413 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004414 Py_ssize_t startinpos;
4415 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004417 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004418 const char *errmsg = "";
4419 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004420 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004421 unsigned int base64bits = 0;
4422 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004423 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004424 PyObject *errorHandler = NULL;
4425 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004427 if (size == 0) {
4428 if (consumed)
4429 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004430 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004431 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004433 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004434 _PyUnicodeWriter_Init(&writer);
4435 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436
4437 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 e = s + size;
4439
4440 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004441 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004442 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004443 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 if (inShift) { /* in a base-64 section */
4446 if (IS_BASE64(ch)) { /* consume a base-64 character */
4447 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4448 base64bits += 6;
4449 s++;
4450 if (base64bits >= 16) {
4451 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004452 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 base64bits -= 16;
4454 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004455 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 if (surrogate) {
4457 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004458 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4459 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004460 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004461 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004463 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 }
4465 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004466 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004467 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004469 }
4470 }
Victor Stinner551ac952011-11-29 22:58:13 +01004471 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 /* first surrogate */
4473 surrogate = outCh;
4474 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004476 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004477 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004478 }
4479 }
4480 }
4481 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004482 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004483 if (base64bits > 0) { /* left-over bits */
4484 if (base64bits >= 6) {
4485 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004486 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 errmsg = "partial character in shift sequence";
4488 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 else {
4491 /* Some bits remain; they should be zero */
4492 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004493 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004494 errmsg = "non-zero padding bits in shift sequence";
4495 goto utf7Error;
4496 }
4497 }
4498 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004499 if (surrogate && DECODE_DIRECT(ch)) {
4500 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4501 goto onError;
4502 }
4503 surrogate = 0;
4504 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004505 /* '-' is absorbed; other terminating
4506 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004507 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004509 }
4510 }
4511 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004512 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513 s++; /* consume '+' */
4514 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004516 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004517 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518 }
4519 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004521 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004522 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004523 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004524 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525 }
4526 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004529 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004530 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004531 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004532 else {
4533 startinpos = s-starts;
4534 s++;
4535 errmsg = "unexpected special character";
4536 goto utf7Error;
4537 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004540 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004541 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 errors, &errorHandler,
4543 "utf7", errmsg,
4544 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004546 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004547 }
4548
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 /* end of string */
4550
4551 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4552 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004553 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 if (surrogate ||
4555 (base64bits >= 6) ||
4556 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004557 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004559 errors, &errorHandler,
4560 "utf7", "unterminated shift sequence",
4561 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004562 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004563 goto onError;
4564 if (s < e)
4565 goto restart;
4566 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004567 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568
4569 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004570 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004572 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004573 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004574 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004575 writer.kind, writer.data, shiftOutStart);
4576 Py_XDECREF(errorHandler);
4577 Py_XDECREF(exc);
4578 _PyUnicodeWriter_Dealloc(&writer);
4579 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004580 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004581 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004582 }
4583 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004584 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004586 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004587
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004588 Py_XDECREF(errorHandler);
4589 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004590 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004591
Benjamin Peterson29060642009-01-31 22:14:21 +00004592 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004593 Py_XDECREF(errorHandler);
4594 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004595 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004596 return NULL;
4597}
4598
4599
Alexander Belopolsky40018472011-02-26 01:02:56 +00004600PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601_PyUnicode_EncodeUTF7(PyObject *str,
4602 int base64SetO,
4603 int base64WhiteSpace,
4604 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004606 int kind;
4607 void *data;
4608 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004609 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004610 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004611 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004612 unsigned int base64bits = 0;
4613 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004614 char * out;
4615 char * start;
4616
Benjamin Petersonbac79492012-01-14 13:34:47 -05004617 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004618 return NULL;
4619 kind = PyUnicode_KIND(str);
4620 data = PyUnicode_DATA(str);
4621 len = PyUnicode_GET_LENGTH(str);
4622
4623 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004624 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004625
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004626 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004627 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004628 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004629 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004630 if (v == NULL)
4631 return NULL;
4632
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004633 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004634 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004635 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004636
Antoine Pitrou244651a2009-05-04 18:56:13 +00004637 if (inShift) {
4638 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4639 /* shifting out */
4640 if (base64bits) { /* output remaining bits */
4641 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4642 base64buffer = 0;
4643 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004644 }
4645 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 /* Characters not in the BASE64 set implicitly unshift the sequence
4647 so no '-' is required, except if the character is itself a '-' */
4648 if (IS_BASE64(ch) || ch == '-') {
4649 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004650 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651 *out++ = (char) ch;
4652 }
4653 else {
4654 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004655 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004656 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004657 else { /* not in a shift sequence */
4658 if (ch == '+') {
4659 *out++ = '+';
4660 *out++ = '-';
4661 }
4662 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4663 *out++ = (char) ch;
4664 }
4665 else {
4666 *out++ = '+';
4667 inShift = 1;
4668 goto encode_char;
4669 }
4670 }
4671 continue;
4672encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004673 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004674 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004675
Antoine Pitrou244651a2009-05-04 18:56:13 +00004676 /* code first surrogate */
4677 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004678 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004679 while (base64bits >= 6) {
4680 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4681 base64bits -= 6;
4682 }
4683 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004684 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004686 base64bits += 16;
4687 base64buffer = (base64buffer << 16) | ch;
4688 while (base64bits >= 6) {
4689 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4690 base64bits -= 6;
4691 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004692 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004693 if (base64bits)
4694 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4695 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004696 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004697 if (_PyBytes_Resize(&v, out - start) < 0)
4698 return NULL;
4699 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004700}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004701PyObject *
4702PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4703 Py_ssize_t size,
4704 int base64SetO,
4705 int base64WhiteSpace,
4706 const char *errors)
4707{
4708 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004709 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004710 if (tmp == NULL)
4711 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004712 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004713 base64WhiteSpace, errors);
4714 Py_DECREF(tmp);
4715 return result;
4716}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004717
Antoine Pitrou244651a2009-05-04 18:56:13 +00004718#undef IS_BASE64
4719#undef FROM_BASE64
4720#undef TO_BASE64
4721#undef DECODE_DIRECT
4722#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004723
Guido van Rossumd57fd912000-03-10 22:53:23 +00004724/* --- UTF-8 Codec -------------------------------------------------------- */
4725
Alexander Belopolsky40018472011-02-26 01:02:56 +00004726PyObject *
4727PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004728 Py_ssize_t size,
4729 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004730{
Walter Dörwald69652032004-09-07 20:24:22 +00004731 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4732}
4733
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734#include "stringlib/asciilib.h"
4735#include "stringlib/codecs.h"
4736#include "stringlib/undef.h"
4737
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004738#include "stringlib/ucs1lib.h"
4739#include "stringlib/codecs.h"
4740#include "stringlib/undef.h"
4741
4742#include "stringlib/ucs2lib.h"
4743#include "stringlib/codecs.h"
4744#include "stringlib/undef.h"
4745
4746#include "stringlib/ucs4lib.h"
4747#include "stringlib/codecs.h"
4748#include "stringlib/undef.h"
4749
Antoine Pitrouab868312009-01-10 15:40:25 +00004750/* Mask to quickly check whether a C 'long' contains a
4751 non-ASCII, UTF8-encoded char. */
4752#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004753# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004754#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004755# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004756#else
4757# error C 'long' size should be either 4 or 8!
4758#endif
4759
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760static Py_ssize_t
4761ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004762{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004764 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004765
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004766 /*
4767 * Issue #17237: m68k is a bit different from most architectures in
4768 * that objects do not use "natural alignment" - for example, int and
4769 * long are only aligned at 2-byte boundaries. Therefore the assert()
4770 * won't work; also, tests have shown that skipping the "optimised
4771 * version" will even speed up m68k.
4772 */
4773#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004775 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4776 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777 /* Fast path, see in STRINGLIB(utf8_decode) for
4778 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004779 /* Help allocation */
4780 const char *_p = p;
4781 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004782 while (_p < aligned_end) {
4783 unsigned long value = *(const unsigned long *) _p;
4784 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004785 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004786 *((unsigned long *)q) = value;
4787 _p += SIZEOF_LONG;
4788 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004789 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004790 p = _p;
4791 while (p < end) {
4792 if ((unsigned char)*p & 0x80)
4793 break;
4794 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004795 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004799#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 while (p < end) {
4801 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4802 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004803 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004804 /* Help allocation */
4805 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806 while (_p < aligned_end) {
4807 unsigned long value = *(unsigned long *) _p;
4808 if (value & ASCII_CHAR_MASK)
4809 break;
4810 _p += SIZEOF_LONG;
4811 }
4812 p = _p;
4813 if (_p == end)
4814 break;
4815 }
4816 if ((unsigned char)*p & 0x80)
4817 break;
4818 ++p;
4819 }
4820 memcpy(dest, start, p - start);
4821 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004822}
Antoine Pitrouab868312009-01-10 15:40:25 +00004823
Victor Stinner785938e2011-12-11 20:09:03 +01004824PyObject *
4825PyUnicode_DecodeUTF8Stateful(const char *s,
4826 Py_ssize_t size,
4827 const char *errors,
4828 Py_ssize_t *consumed)
4829{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004830 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004831 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004832 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833
4834 Py_ssize_t startinpos;
4835 Py_ssize_t endinpos;
4836 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004837 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004838 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004839 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004840
4841 if (size == 0) {
4842 if (consumed)
4843 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004844 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004845 }
4846
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4848 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004849 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 *consumed = 1;
4851 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004852 }
4853
Victor Stinner8f674cc2013-04-17 23:02:17 +02004854 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004855 writer.min_length = size;
4856 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004857 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004858
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004859 writer.pos = ascii_decode(s, end, writer.data);
4860 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004861 while (s < end) {
4862 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004863 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004864
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004866 if (PyUnicode_IS_ASCII(writer.buffer))
4867 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004868 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004869 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004870 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004871 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 } else {
4873 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004874 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004875 }
4876
4877 switch (ch) {
4878 case 0:
4879 if (s == end || consumed)
4880 goto End;
4881 errmsg = "unexpected end of data";
4882 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004883 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884 break;
4885 case 1:
4886 errmsg = "invalid start byte";
4887 startinpos = s - starts;
4888 endinpos = startinpos + 1;
4889 break;
4890 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004891 case 3:
4892 case 4:
Miss Islington (bot)bd482802019-03-30 06:52:41 -07004893 if (s == end || consumed) {
4894 goto End;
4895 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004896 errmsg = "invalid continuation byte";
4897 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004898 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004899 break;
4900 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004901 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004902 goto onError;
4903 continue;
4904 }
4905
Victor Stinner1d65d912015-10-05 13:43:50 +02004906 if (error_handler == _Py_ERROR_UNKNOWN)
4907 error_handler = get_error_handler(errors);
4908
4909 switch (error_handler) {
4910 case _Py_ERROR_IGNORE:
4911 s += (endinpos - startinpos);
4912 break;
4913
4914 case _Py_ERROR_REPLACE:
4915 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4916 goto onError;
4917 s += (endinpos - startinpos);
4918 break;
4919
4920 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004921 {
4922 Py_ssize_t i;
4923
Victor Stinner1d65d912015-10-05 13:43:50 +02004924 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4925 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004926 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004927 ch = (Py_UCS4)(unsigned char)(starts[i]);
4928 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4929 ch + 0xdc00);
4930 writer.pos++;
4931 }
4932 s += (endinpos - startinpos);
4933 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004934 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004935
4936 default:
4937 if (unicode_decode_call_errorhandler_writer(
4938 errors, &error_handler_obj,
4939 "utf-8", errmsg,
4940 &starts, &end, &startinpos, &endinpos, &exc, &s,
4941 &writer))
4942 goto onError;
4943 }
Victor Stinner785938e2011-12-11 20:09:03 +01004944 }
4945
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004947 if (consumed)
4948 *consumed = s - starts;
4949
Victor Stinner1d65d912015-10-05 13:43:50 +02004950 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004952 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004953
4954onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004955 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004957 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004958 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004959}
4960
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004961
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004962/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4963 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004964
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004965 On success, write a pointer to a newly allocated wide character string into
4966 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4967 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004968
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004969 On memory allocation failure, return -1.
4970
4971 On decoding error (if surrogateescape is zero), return -2. If wlen is
4972 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4973 is not NULL, write the decoding error message into *reason. */
4974int
4975_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
4976 const char **reason, int surrogateescape)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004977{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004978 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004979 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004980 wchar_t *unicode;
4981 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004982
4983 /* Note: size will always be longer than the resulting Unicode
4984 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004985 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004986 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004987 }
4988
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004989 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004990 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004991 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004992 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004993
4994 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004995 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004997 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004998 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004999#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005000 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005001#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005003#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 if (ch > 0xFF) {
5005#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005006 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005007#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005008 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005009 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005010 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5011 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5012#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005013 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005014 else {
5015 if (!ch && s == e)
5016 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005017 if (!surrogateescape) {
5018 PyMem_RawFree(unicode );
5019 if (reason != NULL) {
5020 switch (ch) {
5021 case 0:
5022 *reason = "unexpected end of data";
5023 break;
5024 case 1:
5025 *reason = "invalid start byte";
5026 break;
5027 /* 2, 3, 4 */
5028 default:
5029 *reason = "invalid continuation byte";
5030 break;
5031 }
5032 }
5033 if (wlen != NULL) {
5034 *wlen = s - orig_s;
5035 }
5036 return -2;
5037 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005038 /* surrogateescape */
5039 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5040 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005041 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005042 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005043 if (wlen) {
5044 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005045 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005046 *wstr = unicode;
5047 return 0;
5048}
5049
5050wchar_t*
5051_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5052{
5053 wchar_t *wstr;
5054 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5055 if (res != 0) {
5056 return NULL;
5057 }
5058 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005059}
5060
Antoine Pitrouab868312009-01-10 15:40:25 +00005061
Victor Stinnere47e6982017-12-21 15:45:16 +01005062/* UTF-8 encoder using the surrogateescape error handler .
5063
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005064 On success, return 0 and write the newly allocated character string (use
5065 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005066
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005067 On encoding failure, return -2 and write the position of the invalid
5068 surrogate character into *error_pos (if error_pos is set) and the decoding
5069 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005070
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005071 On memory allocation failure, return -1. */
5072int
5073_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
5074 const char **reason, int raw_malloc, int surrogateescape)
Victor Stinnere47e6982017-12-21 15:45:16 +01005075{
5076 const Py_ssize_t max_char_size = 4;
5077 Py_ssize_t len = wcslen(text);
5078
5079 assert(len >= 0);
5080
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005081 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5082 return -1;
5083 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005084 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005085 if (raw_malloc) {
5086 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005087 }
5088 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005089 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005090 }
5091 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005092 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005093 }
5094
5095 char *p = bytes;
5096 Py_ssize_t i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005097 for (i = 0; i < len; i++) {
5098 Py_UCS4 ch = text[i];
Victor Stinnere47e6982017-12-21 15:45:16 +01005099
5100 if (ch < 0x80) {
5101 /* Encode ASCII */
5102 *p++ = (char) ch;
5103
5104 }
5105 else if (ch < 0x0800) {
5106 /* Encode Latin-1 */
5107 *p++ = (char)(0xc0 | (ch >> 6));
5108 *p++ = (char)(0x80 | (ch & 0x3f));
5109 }
5110 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5111 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005112 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005113 if (error_pos != NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005114 *error_pos = (size_t)i;
Victor Stinnere47e6982017-12-21 15:45:16 +01005115 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005116 if (reason != NULL) {
5117 *reason = "encoding error";
5118 }
5119 if (raw_malloc) {
5120 PyMem_RawFree(bytes);
5121 }
5122 else {
5123 PyMem_Free(bytes);
5124 }
5125 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005126 }
5127 *p++ = (char)(ch & 0xff);
5128 }
5129 else if (ch < 0x10000) {
5130 *p++ = (char)(0xe0 | (ch >> 12));
5131 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5132 *p++ = (char)(0x80 | (ch & 0x3f));
5133 }
5134 else { /* ch >= 0x10000 */
5135 assert(ch <= MAX_UNICODE);
5136 /* Encode UCS4 Unicode ordinals */
5137 *p++ = (char)(0xf0 | (ch >> 18));
5138 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5139 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5140 *p++ = (char)(0x80 | (ch & 0x3f));
5141 }
5142 }
5143 *p++ = '\0';
5144
5145 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005146 char *bytes2;
5147 if (raw_malloc) {
5148 bytes2 = PyMem_RawRealloc(bytes, final_size);
5149 }
5150 else {
5151 bytes2 = PyMem_Realloc(bytes, final_size);
5152 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005153 if (bytes2 == NULL) {
5154 if (error_pos != NULL) {
5155 *error_pos = (size_t)-1;
5156 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005157 if (raw_malloc) {
5158 PyMem_RawFree(bytes);
5159 }
5160 else {
5161 PyMem_Free(bytes);
5162 }
5163 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005164 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005165 *str = bytes2;
5166 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005167}
5168
5169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005170/* Primary internal function which creates utf8 encoded bytes objects.
5171
5172 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005173 and allocate exactly as much space needed at the end. Else allocate the
5174 maximum possible needed (4 result bytes per Unicode character), and return
5175 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005176*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005177PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005178_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005179{
Victor Stinner6099a032011-12-18 14:22:26 +01005180 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005181 void *data;
5182 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005184 if (!PyUnicode_Check(unicode)) {
5185 PyErr_BadArgument();
5186 return NULL;
5187 }
5188
5189 if (PyUnicode_READY(unicode) == -1)
5190 return NULL;
5191
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005192 if (PyUnicode_UTF8(unicode))
5193 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5194 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005195
5196 kind = PyUnicode_KIND(unicode);
5197 data = PyUnicode_DATA(unicode);
5198 size = PyUnicode_GET_LENGTH(unicode);
5199
Benjamin Petersonead6b532011-12-20 17:23:42 -06005200 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005201 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005202 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005203 case PyUnicode_1BYTE_KIND:
5204 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5205 assert(!PyUnicode_IS_ASCII(unicode));
5206 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5207 case PyUnicode_2BYTE_KIND:
5208 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5209 case PyUnicode_4BYTE_KIND:
5210 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005211 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212}
5213
Alexander Belopolsky40018472011-02-26 01:02:56 +00005214PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005215PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5216 Py_ssize_t size,
5217 const char *errors)
5218{
5219 PyObject *v, *unicode;
5220
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005221 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005222 if (unicode == NULL)
5223 return NULL;
5224 v = _PyUnicode_AsUTF8String(unicode, errors);
5225 Py_DECREF(unicode);
5226 return v;
5227}
5228
5229PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005230PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005231{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005232 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005233}
5234
Walter Dörwald41980ca2007-08-16 21:55:45 +00005235/* --- UTF-32 Codec ------------------------------------------------------- */
5236
5237PyObject *
5238PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 Py_ssize_t size,
5240 const char *errors,
5241 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005242{
5243 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5244}
5245
5246PyObject *
5247PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 Py_ssize_t size,
5249 const char *errors,
5250 int *byteorder,
5251 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005252{
5253 const char *starts = s;
5254 Py_ssize_t startinpos;
5255 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005256 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005257 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005258 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005259 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005260 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005261 PyObject *errorHandler = NULL;
5262 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005263
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264 q = (unsigned char *)s;
5265 e = q + size;
5266
5267 if (byteorder)
5268 bo = *byteorder;
5269
5270 /* Check for BOM marks (U+FEFF) in the input and adjust current
5271 byte order setting accordingly. In native mode, the leading BOM
5272 mark is skipped, in all other modes, it is copied to the output
5273 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005275 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005276 if (bom == 0x0000FEFF) {
5277 bo = -1;
5278 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005279 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005280 else if (bom == 0xFFFE0000) {
5281 bo = 1;
5282 q += 4;
5283 }
5284 if (byteorder)
5285 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005286 }
5287
Victor Stinnere64322e2012-10-30 23:12:47 +01005288 if (q == e) {
5289 if (consumed)
5290 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005291 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005292 }
5293
Victor Stinnere64322e2012-10-30 23:12:47 +01005294#ifdef WORDS_BIGENDIAN
5295 le = bo < 0;
5296#else
5297 le = bo <= 0;
5298#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005299 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005300
Victor Stinner8f674cc2013-04-17 23:02:17 +02005301 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005302 writer.min_length = (e - q + 3) / 4;
5303 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005304 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005305
Victor Stinnere64322e2012-10-30 23:12:47 +01005306 while (1) {
5307 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005308 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005309
Victor Stinnere64322e2012-10-30 23:12:47 +01005310 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005311 enum PyUnicode_Kind kind = writer.kind;
5312 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005313 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005314 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005315 if (le) {
5316 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005317 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005318 if (ch > maxch)
5319 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005320 if (kind != PyUnicode_1BYTE_KIND &&
5321 Py_UNICODE_IS_SURROGATE(ch))
5322 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005323 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005324 q += 4;
5325 } while (q <= last);
5326 }
5327 else {
5328 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005329 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005330 if (ch > maxch)
5331 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005332 if (kind != PyUnicode_1BYTE_KIND &&
5333 Py_UNICODE_IS_SURROGATE(ch))
5334 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005336 q += 4;
5337 } while (q <= last);
5338 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005339 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005340 }
5341
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005342 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005343 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005344 startinpos = ((const char *)q) - starts;
5345 endinpos = startinpos + 4;
5346 }
5347 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005348 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005350 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005352 startinpos = ((const char *)q) - starts;
5353 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005354 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005355 else {
5356 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005357 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005358 goto onError;
5359 q += 4;
5360 continue;
5361 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005362 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005363 startinpos = ((const char *)q) - starts;
5364 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005365 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005366
5367 /* The remaining input chars are ignored if the callback
5368 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005369 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005370 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005371 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005373 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005375 }
5376
Walter Dörwald41980ca2007-08-16 21:55:45 +00005377 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005379
Walter Dörwald41980ca2007-08-16 21:55:45 +00005380 Py_XDECREF(errorHandler);
5381 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005382 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005383
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005385 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005386 Py_XDECREF(errorHandler);
5387 Py_XDECREF(exc);
5388 return NULL;
5389}
5390
5391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005392_PyUnicode_EncodeUTF32(PyObject *str,
5393 const char *errors,
5394 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005395{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005396 enum PyUnicode_Kind kind;
5397 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005398 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005399 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005400 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005401#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005403#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005404 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005405#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005406 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005407 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005408 PyObject *errorHandler = NULL;
5409 PyObject *exc = NULL;
5410 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005411
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005412 if (!PyUnicode_Check(str)) {
5413 PyErr_BadArgument();
5414 return NULL;
5415 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005416 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005417 return NULL;
5418 kind = PyUnicode_KIND(str);
5419 data = PyUnicode_DATA(str);
5420 len = PyUnicode_GET_LENGTH(str);
5421
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005422 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005423 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005424 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005425 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005426 if (v == NULL)
5427 return NULL;
5428
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005429 /* output buffer is 4-bytes aligned */
5430 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005431 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005432 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005433 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005434 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005435 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005436
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005437 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005438 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005439 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005440 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005441 else
5442 encoding = "utf-32";
5443
5444 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005445 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5446 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005447 }
5448
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005449 pos = 0;
5450 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005451 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005452
5453 if (kind == PyUnicode_2BYTE_KIND) {
5454 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5455 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005456 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005457 else {
5458 assert(kind == PyUnicode_4BYTE_KIND);
5459 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5460 &out, native_ordering);
5461 }
5462 if (pos == len)
5463 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005464
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005465 rep = unicode_encode_call_errorhandler(
5466 errors, &errorHandler,
5467 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005468 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 if (!rep)
5470 goto error;
5471
5472 if (PyBytes_Check(rep)) {
5473 repsize = PyBytes_GET_SIZE(rep);
5474 if (repsize & 3) {
5475 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005476 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005477 "surrogates not allowed");
5478 goto error;
5479 }
5480 moreunits = repsize / 4;
5481 }
5482 else {
5483 assert(PyUnicode_Check(rep));
5484 if (PyUnicode_READY(rep) < 0)
5485 goto error;
5486 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5487 if (!PyUnicode_IS_ASCII(rep)) {
5488 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005489 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005490 "surrogates not allowed");
5491 goto error;
5492 }
5493 }
5494
5495 /* four bytes are reserved for each surrogate */
5496 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005497 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005498 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005499 /* integer overflow */
5500 PyErr_NoMemory();
5501 goto error;
5502 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005503 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005504 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005505 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005506 }
5507
5508 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005509 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005510 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005511 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005512 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005513 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5514 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005515 }
5516
5517 Py_CLEAR(rep);
5518 }
5519
5520 /* Cut back to size actually needed. This is necessary for, for example,
5521 encoding of a string containing isolated surrogates and the 'ignore'
5522 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005523 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005524 if (nsize != PyBytes_GET_SIZE(v))
5525 _PyBytes_Resize(&v, nsize);
5526 Py_XDECREF(errorHandler);
5527 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005528 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005529 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005530 error:
5531 Py_XDECREF(rep);
5532 Py_XDECREF(errorHandler);
5533 Py_XDECREF(exc);
5534 Py_XDECREF(v);
5535 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005536}
5537
Alexander Belopolsky40018472011-02-26 01:02:56 +00005538PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005539PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5540 Py_ssize_t size,
5541 const char *errors,
5542 int byteorder)
5543{
5544 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005545 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005546 if (tmp == NULL)
5547 return NULL;
5548 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5549 Py_DECREF(tmp);
5550 return result;
5551}
5552
5553PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005554PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005555{
Victor Stinnerb960b342011-11-20 19:12:52 +01005556 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005557}
5558
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559/* --- UTF-16 Codec ------------------------------------------------------- */
5560
Tim Peters772747b2001-08-09 22:21:55 +00005561PyObject *
5562PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005563 Py_ssize_t size,
5564 const char *errors,
5565 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566{
Walter Dörwald69652032004-09-07 20:24:22 +00005567 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5568}
5569
5570PyObject *
5571PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005572 Py_ssize_t size,
5573 const char *errors,
5574 int *byteorder,
5575 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005576{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005577 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005578 Py_ssize_t startinpos;
5579 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005580 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005582 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005583 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005584 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005585 PyObject *errorHandler = NULL;
5586 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005587 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005588
Tim Peters772747b2001-08-09 22:21:55 +00005589 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005591
5592 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005593 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005594
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005595 /* Check for BOM marks (U+FEFF) in the input and adjust current
5596 byte order setting accordingly. In native mode, the leading BOM
5597 mark is skipped, in all other modes, it is copied to the output
5598 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 if (bo == 0 && size >= 2) {
5600 const Py_UCS4 bom = (q[1] << 8) | q[0];
5601 if (bom == 0xFEFF) {
5602 q += 2;
5603 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005604 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005605 else if (bom == 0xFFFE) {
5606 q += 2;
5607 bo = 1;
5608 }
5609 if (byteorder)
5610 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005611 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 if (q == e) {
5614 if (consumed)
5615 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005616 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005617 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005618
Christian Heimes743e0cd2012-10-17 23:52:17 +02005619#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005620 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005621 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005622#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005623 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005624 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005625#endif
Tim Peters772747b2001-08-09 22:21:55 +00005626
Antoine Pitrou63065d72012-05-15 23:48:04 +02005627 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang86fdad02018-01-31 20:48:05 +08005628 character count normally. Error handler will take care of
5629 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005630 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005631 writer.min_length = (e - q + 1) / 2;
5632 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005633 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005634
Antoine Pitrou63065d72012-05-15 23:48:04 +02005635 while (1) {
5636 Py_UCS4 ch = 0;
5637 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005638 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005639 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005640 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005641 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005642 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005643 native_ordering);
5644 else
5645 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005646 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005647 native_ordering);
5648 } else if (kind == PyUnicode_2BYTE_KIND) {
5649 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005650 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005651 native_ordering);
5652 } else {
5653 assert(kind == PyUnicode_4BYTE_KIND);
5654 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005655 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005656 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005657 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005658 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005659
Antoine Pitrou63065d72012-05-15 23:48:04 +02005660 switch (ch)
5661 {
5662 case 0:
5663 /* remaining byte at the end? (size should be even) */
5664 if (q == e || consumed)
5665 goto End;
5666 errmsg = "truncated data";
5667 startinpos = ((const char *)q) - starts;
5668 endinpos = ((const char *)e) - starts;
5669 break;
5670 /* The remaining input chars are ignored if the callback
5671 chooses to skip the input */
5672 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005673 q -= 2;
5674 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005675 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005676 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005677 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005678 endinpos = ((const char *)e) - starts;
5679 break;
5680 case 2:
5681 errmsg = "illegal encoding";
5682 startinpos = ((const char *)q) - 2 - starts;
5683 endinpos = startinpos + 2;
5684 break;
5685 case 3:
5686 errmsg = "illegal UTF-16 surrogate";
5687 startinpos = ((const char *)q) - 4 - starts;
5688 endinpos = startinpos + 2;
5689 break;
5690 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005691 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005692 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 continue;
5694 }
5695
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005696 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005697 errors,
5698 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005699 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005700 &starts,
5701 (const char **)&e,
5702 &startinpos,
5703 &endinpos,
5704 &exc,
5705 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005706 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005707 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005708 }
5709
Antoine Pitrou63065d72012-05-15 23:48:04 +02005710End:
Walter Dörwald69652032004-09-07 20:24:22 +00005711 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005712 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005713
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005714 Py_XDECREF(errorHandler);
5715 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005716 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005719 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005720 Py_XDECREF(errorHandler);
5721 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 return NULL;
5723}
5724
Tim Peters772747b2001-08-09 22:21:55 +00005725PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726_PyUnicode_EncodeUTF16(PyObject *str,
5727 const char *errors,
5728 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005730 enum PyUnicode_Kind kind;
5731 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005732 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005733 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005734 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005735 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005736#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005737 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005738#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005739 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005740#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005741 const char *encoding;
5742 Py_ssize_t nsize, pos;
5743 PyObject *errorHandler = NULL;
5744 PyObject *exc = NULL;
5745 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005746
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005747 if (!PyUnicode_Check(str)) {
5748 PyErr_BadArgument();
5749 return NULL;
5750 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005751 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005752 return NULL;
5753 kind = PyUnicode_KIND(str);
5754 data = PyUnicode_DATA(str);
5755 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005756
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005757 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005758 if (kind == PyUnicode_4BYTE_KIND) {
5759 const Py_UCS4 *in = (const Py_UCS4 *)data;
5760 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005761 while (in < end) {
5762 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005763 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005764 }
5765 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005766 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005767 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005769 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005770 nsize = len + pairs + (byteorder == 0);
5771 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005772 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005774 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005776 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005777 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005778 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005779 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005780 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005781 }
5782 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005783 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005784 }
Tim Peters772747b2001-08-09 22:21:55 +00005785
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005786 if (kind == PyUnicode_1BYTE_KIND) {
5787 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5788 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005789 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005790
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005791 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005792 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005793 }
5794 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005795 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005796 }
5797 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005798 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005799 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005800
5801 pos = 0;
5802 while (pos < len) {
5803 Py_ssize_t repsize, moreunits;
5804
5805 if (kind == PyUnicode_2BYTE_KIND) {
5806 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5807 &out, native_ordering);
5808 }
5809 else {
5810 assert(kind == PyUnicode_4BYTE_KIND);
5811 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5812 &out, native_ordering);
5813 }
5814 if (pos == len)
5815 break;
5816
5817 rep = unicode_encode_call_errorhandler(
5818 errors, &errorHandler,
5819 encoding, "surrogates not allowed",
5820 str, &exc, pos, pos + 1, &pos);
5821 if (!rep)
5822 goto error;
5823
5824 if (PyBytes_Check(rep)) {
5825 repsize = PyBytes_GET_SIZE(rep);
5826 if (repsize & 1) {
5827 raise_encode_exception(&exc, encoding,
5828 str, pos - 1, pos,
5829 "surrogates not allowed");
5830 goto error;
5831 }
5832 moreunits = repsize / 2;
5833 }
5834 else {
5835 assert(PyUnicode_Check(rep));
5836 if (PyUnicode_READY(rep) < 0)
5837 goto error;
5838 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5839 if (!PyUnicode_IS_ASCII(rep)) {
5840 raise_encode_exception(&exc, encoding,
5841 str, pos - 1, pos,
5842 "surrogates not allowed");
5843 goto error;
5844 }
5845 }
5846
5847 /* two bytes are reserved for each surrogate */
5848 if (moreunits > 1) {
5849 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005850 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005851 /* integer overflow */
5852 PyErr_NoMemory();
5853 goto error;
5854 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005855 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005856 goto error;
5857 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5858 }
5859
5860 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005861 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005862 out += moreunits;
5863 } else /* rep is unicode */ {
5864 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5865 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5866 &out, native_ordering);
5867 }
5868
5869 Py_CLEAR(rep);
5870 }
5871
5872 /* Cut back to size actually needed. This is necessary for, for example,
5873 encoding of a string containing isolated surrogates and the 'ignore' handler
5874 is used. */
5875 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5876 if (nsize != PyBytes_GET_SIZE(v))
5877 _PyBytes_Resize(&v, nsize);
5878 Py_XDECREF(errorHandler);
5879 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005880 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005881 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005882 error:
5883 Py_XDECREF(rep);
5884 Py_XDECREF(errorHandler);
5885 Py_XDECREF(exc);
5886 Py_XDECREF(v);
5887 return NULL;
5888#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889}
5890
Alexander Belopolsky40018472011-02-26 01:02:56 +00005891PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005892PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5893 Py_ssize_t size,
5894 const char *errors,
5895 int byteorder)
5896{
5897 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005898 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005899 if (tmp == NULL)
5900 return NULL;
5901 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5902 Py_DECREF(tmp);
5903 return result;
5904}
5905
5906PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005907PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005909 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910}
5911
5912/* --- Unicode Escape Codec ----------------------------------------------- */
5913
Fredrik Lundh06d12682001-01-24 07:59:11 +00005914static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005915
Alexander Belopolsky40018472011-02-26 01:02:56 +00005916PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005917_PyUnicode_DecodeUnicodeEscape(const char *s,
5918 Py_ssize_t size,
5919 const char *errors,
5920 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005922 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005923 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005925 PyObject *errorHandler = NULL;
5926 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005927
Eric V. Smith42454af2016-10-31 09:22:08 -04005928 // so we can remember if we've seen an invalid escape char or not
5929 *first_invalid_escape = NULL;
5930
Victor Stinner62ec3312016-09-06 17:04:34 -07005931 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005932 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005933 }
5934 /* Escaped strings will always be longer than the resulting
5935 Unicode string, so we start with size here and then reduce the
5936 length after conversion to the true value.
5937 (but if the error callback returns a long replacement string
5938 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005939 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005940 writer.min_length = size;
5941 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5942 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005943 }
5944
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945 end = s + size;
5946 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005947 unsigned char c = (unsigned char) *s++;
5948 Py_UCS4 ch;
5949 int count;
5950 Py_ssize_t startinpos;
5951 Py_ssize_t endinpos;
5952 const char *message;
5953
5954#define WRITE_ASCII_CHAR(ch) \
5955 do { \
5956 assert(ch <= 127); \
5957 assert(writer.pos < writer.size); \
5958 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5959 } while(0)
5960
5961#define WRITE_CHAR(ch) \
5962 do { \
5963 if (ch <= writer.maxchar) { \
5964 assert(writer.pos < writer.size); \
5965 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5966 } \
5967 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5968 goto onError; \
5969 } \
5970 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
5972 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005973 if (c != '\\') {
5974 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005975 continue;
5976 }
5977
Victor Stinner62ec3312016-09-06 17:04:34 -07005978 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005980 if (s >= end) {
5981 message = "\\ at end of string";
5982 goto error;
5983 }
5984 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005985
Victor Stinner62ec3312016-09-06 17:04:34 -07005986 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005987 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988
Benjamin Peterson29060642009-01-31 22:14:21 +00005989 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 case '\n': continue;
5991 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5992 case '\'': WRITE_ASCII_CHAR('\''); continue;
5993 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5994 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005995 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005996 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5997 case 't': WRITE_ASCII_CHAR('\t'); continue;
5998 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5999 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006000 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006002 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006003 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004
Benjamin Peterson29060642009-01-31 22:14:21 +00006005 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 case '0': case '1': case '2': case '3':
6007 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006008 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006009 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006010 ch = (ch<<3) + *s++ - '0';
6011 if (s < end && '0' <= *s && *s <= '7') {
6012 ch = (ch<<3) + *s++ - '0';
6013 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006015 WRITE_CHAR(ch);
6016 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017
Benjamin Peterson29060642009-01-31 22:14:21 +00006018 /* hex escapes */
6019 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006020 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006021 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006022 message = "truncated \\xXX escape";
6023 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006027 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006028 message = "truncated \\uXXXX escape";
6029 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006032 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006033 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006034 message = "truncated \\UXXXXXXXX escape";
6035 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006036 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006037 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 ch <<= 4;
6039 if (c >= '0' && c <= '9') {
6040 ch += c - '0';
6041 }
6042 else if (c >= 'a' && c <= 'f') {
6043 ch += c - ('a' - 10);
6044 }
6045 else if (c >= 'A' && c <= 'F') {
6046 ch += c - ('A' - 10);
6047 }
6048 else {
6049 break;
6050 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006051 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006052 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006053 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006054 }
6055
6056 /* when we get here, ch is a 32-bit unicode character */
6057 if (ch > MAX_UNICODE) {
6058 message = "illegal Unicode character";
6059 goto error;
6060 }
6061
6062 WRITE_CHAR(ch);
6063 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006064
Benjamin Peterson29060642009-01-31 22:14:21 +00006065 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006066 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006067 if (ucnhash_CAPI == NULL) {
6068 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006069 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6070 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 if (ucnhash_CAPI == NULL) {
6072 PyErr_SetString(
6073 PyExc_UnicodeError,
6074 "\\N escapes not supported (can't load unicodedata module)"
6075 );
6076 goto onError;
6077 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006078 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006079
6080 message = "malformed \\N character escape";
Miss Islington (bot)9fbcb142018-11-13 16:39:36 -08006081 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006082 const char *start = ++s;
6083 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006084 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006085 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006086 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006087 namelen = s - start;
6088 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006089 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006090 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006091 ch = 0xffffffff; /* in case 'getcode' messes up */
6092 if (namelen <= INT_MAX &&
6093 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6094 &ch, 0)) {
6095 assert(ch <= MAX_UNICODE);
6096 WRITE_CHAR(ch);
6097 continue;
6098 }
6099 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006100 }
6101 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006102 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006103
6104 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006105 if (*first_invalid_escape == NULL) {
6106 *first_invalid_escape = s-1; /* Back up one char, since we've
6107 already incremented s. */
6108 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006109 WRITE_ASCII_CHAR('\\');
6110 WRITE_CHAR(c);
6111 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006113
6114 error:
6115 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006116 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006117 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006118 errors, &errorHandler,
6119 "unicodeescape", message,
6120 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006121 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006122 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006123 }
Miss Islington (bot)09819ef2018-02-12 23:15:57 -08006124 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006125
6126#undef WRITE_ASCII_CHAR
6127#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006129
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006130 Py_XDECREF(errorHandler);
6131 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006132 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006133
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006135 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006136 Py_XDECREF(errorHandler);
6137 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 return NULL;
6139}
6140
Eric V. Smith42454af2016-10-31 09:22:08 -04006141PyObject *
6142PyUnicode_DecodeUnicodeEscape(const char *s,
6143 Py_ssize_t size,
6144 const char *errors)
6145{
6146 const char *first_invalid_escape;
6147 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6148 &first_invalid_escape);
6149 if (result == NULL)
6150 return NULL;
6151 if (first_invalid_escape != NULL) {
6152 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6153 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006154 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006155 Py_DECREF(result);
6156 return NULL;
6157 }
6158 }
6159 return result;
6160}
6161
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006162/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163
Alexander Belopolsky40018472011-02-26 01:02:56 +00006164PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006166{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006168 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006170 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006172 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173
Ezio Melottie7f90372012-10-05 03:33:31 +03006174 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006175 escape.
6176
Ezio Melottie7f90372012-10-05 03:33:31 +03006177 For UCS1 strings it's '\xxx', 4 bytes per source character.
6178 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6179 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006180 */
6181
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006182 if (!PyUnicode_Check(unicode)) {
6183 PyErr_BadArgument();
6184 return NULL;
6185 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006186 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006188 }
Victor Stinner358af132015-10-12 22:36:57 +02006189
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 if (len == 0) {
6192 return PyBytes_FromStringAndSize(NULL, 0);
6193 }
6194
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006195 kind = PyUnicode_KIND(unicode);
6196 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006197 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6198 bytes, and 1 byte characters 4. */
6199 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006200 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006201 return PyErr_NoMemory();
6202 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006203 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006204 if (repr == NULL) {
6205 return NULL;
6206 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006207
Victor Stinner62ec3312016-09-06 17:04:34 -07006208 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006209 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006210 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006211
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 /* U+0000-U+00ff range */
6213 if (ch < 0x100) {
6214 if (ch >= ' ' && ch < 127) {
6215 if (ch != '\\') {
6216 /* Copy printable US ASCII as-is */
6217 *p++ = (char) ch;
6218 }
6219 /* Escape backslashes */
6220 else {
6221 *p++ = '\\';
6222 *p++ = '\\';
6223 }
6224 }
Victor Stinner358af132015-10-12 22:36:57 +02006225
Victor Stinner62ec3312016-09-06 17:04:34 -07006226 /* Map special whitespace to '\t', \n', '\r' */
6227 else if (ch == '\t') {
6228 *p++ = '\\';
6229 *p++ = 't';
6230 }
6231 else if (ch == '\n') {
6232 *p++ = '\\';
6233 *p++ = 'n';
6234 }
6235 else if (ch == '\r') {
6236 *p++ = '\\';
6237 *p++ = 'r';
6238 }
6239
6240 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6241 else {
6242 *p++ = '\\';
6243 *p++ = 'x';
6244 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6245 *p++ = Py_hexdigits[ch & 0x000F];
6246 }
Tim Petersced69f82003-09-16 20:30:58 +00006247 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006248 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006250 *p++ = '\\';
6251 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006252 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6253 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6254 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6255 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006256 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006257 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6258 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006259
Victor Stinner62ec3312016-09-06 17:04:34 -07006260 /* Make sure that the first two digits are zero */
6261 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006262 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006263 *p++ = 'U';
6264 *p++ = '0';
6265 *p++ = '0';
6266 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6267 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6268 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6269 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6270 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6271 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006272 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274
Victor Stinner62ec3312016-09-06 17:04:34 -07006275 assert(p - PyBytes_AS_STRING(repr) > 0);
6276 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6277 return NULL;
6278 }
6279 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006280}
6281
Alexander Belopolsky40018472011-02-26 01:02:56 +00006282PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006283PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6284 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006285{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006286 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006287 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006288 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006289 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006290 }
6291
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006292 result = PyUnicode_AsUnicodeEscapeString(tmp);
6293 Py_DECREF(tmp);
6294 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295}
6296
6297/* --- Raw Unicode Escape Codec ------------------------------------------- */
6298
Alexander Belopolsky40018472011-02-26 01:02:56 +00006299PyObject *
6300PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006301 Py_ssize_t size,
6302 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006304 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006305 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006306 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006307 PyObject *errorHandler = NULL;
6308 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006309
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006311 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006312 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006313
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 /* Escaped strings will always be longer than the resulting
6315 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006316 length after conversion to the true value. (But decoding error
6317 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006318 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 writer.min_length = size;
6320 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6321 goto onError;
6322 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006323
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324 end = s + size;
6325 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 unsigned char c = (unsigned char) *s++;
6327 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006328 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006329 Py_ssize_t startinpos;
6330 Py_ssize_t endinpos;
6331 const char *message;
6332
6333#define WRITE_CHAR(ch) \
6334 do { \
6335 if (ch <= writer.maxchar) { \
6336 assert(writer.pos < writer.size); \
6337 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6338 } \
6339 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6340 goto onError; \
6341 } \
6342 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343
Benjamin Peterson29060642009-01-31 22:14:21 +00006344 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006345 if (c != '\\' || s >= end) {
6346 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006347 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006348 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006349
Victor Stinner62ec3312016-09-06 17:04:34 -07006350 c = (unsigned char) *s++;
6351 if (c == 'u') {
6352 count = 4;
6353 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006355 else if (c == 'U') {
6356 count = 8;
6357 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006358 }
6359 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006360 assert(writer.pos < writer.size);
6361 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6362 WRITE_CHAR(c);
6363 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006364 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006365 startinpos = s - starts - 2;
6366
6367 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6368 for (ch = 0; count && s < end; ++s, --count) {
6369 c = (unsigned char)*s;
6370 ch <<= 4;
6371 if (c >= '0' && c <= '9') {
6372 ch += c - '0';
6373 }
6374 else if (c >= 'a' && c <= 'f') {
6375 ch += c - ('a' - 10);
6376 }
6377 else if (c >= 'A' && c <= 'F') {
6378 ch += c - ('A' - 10);
6379 }
6380 else {
6381 break;
6382 }
6383 }
6384 if (!count) {
6385 if (ch <= MAX_UNICODE) {
6386 WRITE_CHAR(ch);
6387 continue;
6388 }
6389 message = "\\Uxxxxxxxx out of range";
6390 }
6391
6392 endinpos = s-starts;
6393 writer.min_length = end - s + writer.pos;
6394 if (unicode_decode_call_errorhandler_writer(
6395 errors, &errorHandler,
6396 "rawunicodeescape", message,
6397 &starts, &end, &startinpos, &endinpos, &exc, &s,
6398 &writer)) {
6399 goto onError;
6400 }
Miss Islington (bot)09819ef2018-02-12 23:15:57 -08006401 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006402
6403#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 Py_XDECREF(errorHandler);
6406 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006407 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006408
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006410 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 Py_XDECREF(errorHandler);
6412 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006414
Guido van Rossumd57fd912000-03-10 22:53:23 +00006415}
6416
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006417
Alexander Belopolsky40018472011-02-26 01:02:56 +00006418PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006419PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006420{
Victor Stinner62ec3312016-09-06 17:04:34 -07006421 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006422 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006423 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006424 int kind;
6425 void *data;
6426 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006428 if (!PyUnicode_Check(unicode)) {
6429 PyErr_BadArgument();
6430 return NULL;
6431 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006432 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006433 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006434 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006435 kind = PyUnicode_KIND(unicode);
6436 data = PyUnicode_DATA(unicode);
6437 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006438 if (kind == PyUnicode_1BYTE_KIND) {
6439 return PyBytes_FromStringAndSize(data, len);
6440 }
Victor Stinner0e368262011-11-10 20:12:49 +01006441
Victor Stinner62ec3312016-09-06 17:04:34 -07006442 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6443 bytes, and 1 byte characters 4. */
6444 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006445
Victor Stinner62ec3312016-09-06 17:04:34 -07006446 if (len > PY_SSIZE_T_MAX / expandsize) {
6447 return PyErr_NoMemory();
6448 }
6449 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6450 if (repr == NULL) {
6451 return NULL;
6452 }
6453 if (len == 0) {
6454 return repr;
6455 }
6456
6457 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006458 for (pos = 0; pos < len; pos++) {
6459 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006460
Victor Stinner62ec3312016-09-06 17:04:34 -07006461 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6462 if (ch < 0x100) {
6463 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006464 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006465 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6466 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006467 *p++ = '\\';
6468 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006469 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6470 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6471 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6472 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006473 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006474 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6475 else {
6476 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6477 *p++ = '\\';
6478 *p++ = 'U';
6479 *p++ = '0';
6480 *p++ = '0';
6481 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6482 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6483 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6484 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6485 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6486 *p++ = Py_hexdigits[ch & 15];
6487 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006488 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006489
Victor Stinner62ec3312016-09-06 17:04:34 -07006490 assert(p > PyBytes_AS_STRING(repr));
6491 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6492 return NULL;
6493 }
6494 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006495}
6496
Alexander Belopolsky40018472011-02-26 01:02:56 +00006497PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006498PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6499 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006501 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006502 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006503 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006504 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006505 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6506 Py_DECREF(tmp);
6507 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508}
6509
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006510/* --- Unicode Internal Codec ------------------------------------------- */
6511
Alexander Belopolsky40018472011-02-26 01:02:56 +00006512PyObject *
6513_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006514 Py_ssize_t size,
6515 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006516{
6517 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006518 Py_ssize_t startinpos;
6519 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006520 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006521 const char *end;
6522 const char *reason;
6523 PyObject *errorHandler = NULL;
6524 PyObject *exc = NULL;
6525
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006526 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006527 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006528 1))
6529 return NULL;
6530
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006531 if (size < 0) {
6532 PyErr_BadInternalCall();
6533 return NULL;
6534 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006535 if (size == 0)
6536 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006537
Victor Stinner8f674cc2013-04-17 23:02:17 +02006538 _PyUnicodeWriter_Init(&writer);
6539 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6540 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006541 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006542 }
6543 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006544
Victor Stinner8f674cc2013-04-17 23:02:17 +02006545 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006546 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006547 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006548 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006549 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006550 endinpos = end-starts;
6551 reason = "truncated input";
6552 goto error;
6553 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006554 /* We copy the raw representation one byte at a time because the
6555 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006556 ((char *) &uch)[0] = s[0];
6557 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006558#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006559 ((char *) &uch)[2] = s[2];
6560 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006561#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006562 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006563#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006564 /* We have to sanity check the raw data, otherwise doom looms for
6565 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006566 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006567 endinpos = s - starts + Py_UNICODE_SIZE;
6568 reason = "illegal code point (> 0x10FFFF)";
6569 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006570 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006571#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006572 s += Py_UNICODE_SIZE;
6573#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006574 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006575 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006576 Py_UNICODE uch2;
6577 ((char *) &uch2)[0] = s[0];
6578 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006579 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006580 {
Victor Stinner551ac952011-11-29 22:58:13 +01006581 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006582 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006583 }
6584 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006585#endif
6586
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006587 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006588 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006589 continue;
6590
6591 error:
6592 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006593 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006594 errors, &errorHandler,
6595 "unicode_internal", reason,
6596 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006597 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006598 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006599 }
6600
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006601 Py_XDECREF(errorHandler);
6602 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006603 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006604
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006606 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006607 Py_XDECREF(errorHandler);
6608 Py_XDECREF(exc);
6609 return NULL;
6610}
6611
Guido van Rossumd57fd912000-03-10 22:53:23 +00006612/* --- Latin-1 Codec ------------------------------------------------------ */
6613
Alexander Belopolsky40018472011-02-26 01:02:56 +00006614PyObject *
6615PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006616 Py_ssize_t size,
6617 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006618{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006620 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006621}
6622
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006624static void
6625make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006626 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006627 PyObject *unicode,
6628 Py_ssize_t startpos, Py_ssize_t endpos,
6629 const char *reason)
6630{
6631 if (*exceptionObject == NULL) {
6632 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006633 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006634 encoding, unicode, startpos, endpos, reason);
6635 }
6636 else {
6637 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6638 goto onError;
6639 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6640 goto onError;
6641 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6642 goto onError;
6643 return;
6644 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006645 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006646 }
6647}
6648
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006650static void
6651raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006652 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006653 PyObject *unicode,
6654 Py_ssize_t startpos, Py_ssize_t endpos,
6655 const char *reason)
6656{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006657 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006658 encoding, unicode, startpos, endpos, reason);
6659 if (*exceptionObject != NULL)
6660 PyCodec_StrictErrors(*exceptionObject);
6661}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006662
6663/* error handling callback helper:
6664 build arguments, call the callback and check the arguments,
6665 put the result into newpos and return the replacement string, which
6666 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006667static PyObject *
6668unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006669 PyObject **errorHandler,
6670 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006672 Py_ssize_t startpos, Py_ssize_t endpos,
6673 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006674{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006675 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006676 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677 PyObject *restuple;
6678 PyObject *resunicode;
6679
6680 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006684 }
6685
Benjamin Petersonbac79492012-01-14 13:34:47 -05006686 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006687 return NULL;
6688 len = PyUnicode_GET_LENGTH(unicode);
6689
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006690 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006691 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006693 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006694
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006695 restuple = PyObject_CallFunctionObjArgs(
6696 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006700 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 Py_DECREF(restuple);
6702 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006703 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006704 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 &resunicode, newpos)) {
6706 Py_DECREF(restuple);
6707 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006708 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006709 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6710 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6711 Py_DECREF(restuple);
6712 return NULL;
6713 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006714 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 *newpos = len + *newpos;
6716 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006717 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 Py_DECREF(restuple);
6719 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006720 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 Py_INCREF(resunicode);
6722 Py_DECREF(restuple);
6723 return resunicode;
6724}
6725
Alexander Belopolsky40018472011-02-26 01:02:56 +00006726static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006727unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006728 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006729 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006730{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006731 /* input state */
6732 Py_ssize_t pos=0, size;
6733 int kind;
6734 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 /* pointer into the output */
6736 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006737 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6738 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006739 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006740 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006741 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006742 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006743 /* output object */
6744 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006745
Benjamin Petersonbac79492012-01-14 13:34:47 -05006746 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747 return NULL;
6748 size = PyUnicode_GET_LENGTH(unicode);
6749 kind = PyUnicode_KIND(unicode);
6750 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006751 /* allocate enough for a simple encoding without
6752 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006753 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006754 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006755
6756 _PyBytesWriter_Init(&writer);
6757 str = _PyBytesWriter_Alloc(&writer, size);
6758 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006759 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006760
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006761 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006762 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006763
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006765 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006767 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006768 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006769 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006771 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006772 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006773 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006774 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006775 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006776
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006777 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006779
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006780 /* Only overallocate the buffer if it's not the last write */
6781 writer.overallocate = (collend < size);
6782
Benjamin Peterson29060642009-01-31 22:14:21 +00006783 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006784 if (error_handler == _Py_ERROR_UNKNOWN)
6785 error_handler = get_error_handler(errors);
6786
6787 switch (error_handler) {
6788 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006789 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006791
6792 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006793 memset(str, '?', collend - collstart);
6794 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006795 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006796 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006797 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006798 break;
Victor Stinner50149202015-09-22 00:26:54 +02006799
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006800 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006801 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006802 writer.min_size -= (collend - collstart);
6803 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006804 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006805 if (str == NULL)
6806 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006807 pos = collend;
6808 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006809
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006810 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006811 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006812 writer.min_size -= (collend - collstart);
6813 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006814 unicode, collstart, collend);
6815 if (str == NULL)
6816 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006817 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006818 break;
Victor Stinner50149202015-09-22 00:26:54 +02006819
Victor Stinnerc3713e92015-09-29 12:32:13 +02006820 case _Py_ERROR_SURROGATEESCAPE:
6821 for (i = collstart; i < collend; ++i) {
6822 ch = PyUnicode_READ(kind, data, i);
6823 if (ch < 0xdc80 || 0xdcff < ch) {
6824 /* Not a UTF-8b surrogate */
6825 break;
6826 }
6827 *str++ = (char)(ch - 0xdc00);
6828 ++pos;
6829 }
6830 if (i >= collend)
6831 break;
6832 collstart = pos;
6833 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006834 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006835
Benjamin Peterson29060642009-01-31 22:14:21 +00006836 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006837 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6838 encoding, reason, unicode, &exc,
6839 collstart, collend, &newpos);
6840 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006842
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006843 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006844 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006845
Victor Stinner6bd525b2015-10-09 13:10:05 +02006846 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006847 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006848 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006849 PyBytes_AS_STRING(rep),
6850 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006851 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006852 else {
6853 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006854
Victor Stinner6bd525b2015-10-09 13:10:05 +02006855 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006857
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006858 if (limit == 256 ?
6859 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6860 !PyUnicode_IS_ASCII(rep))
6861 {
6862 /* Not all characters are smaller than limit */
6863 raise_encode_exception(&exc, encoding, unicode,
6864 collstart, collend, reason);
6865 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006866 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006867 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6868 str = _PyBytesWriter_WriteBytes(&writer, str,
6869 PyUnicode_DATA(rep),
6870 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 }
Miss Islington (bot)1e596d32018-08-19 16:17:53 -04006872 if (str == NULL)
6873 goto onError;
6874
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006875 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006876 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006877 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006878
6879 /* If overallocation was disabled, ensure that it was the last
6880 write. Otherwise, we missed an optimization */
6881 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006882 }
6883 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006884
Victor Stinner50149202015-09-22 00:26:54 +02006885 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006886 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006887 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006888
6889 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006890 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006891 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006892 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006893 Py_XDECREF(exc);
6894 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006895}
6896
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006897/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006898PyObject *
6899PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006900 Py_ssize_t size,
6901 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006903 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006904 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006905 if (unicode == NULL)
6906 return NULL;
6907 result = unicode_encode_ucs1(unicode, errors, 256);
6908 Py_DECREF(unicode);
6909 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006910}
6911
Alexander Belopolsky40018472011-02-26 01:02:56 +00006912PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006913_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006914{
6915 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 PyErr_BadArgument();
6917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006919 if (PyUnicode_READY(unicode) == -1)
6920 return NULL;
6921 /* Fast path: if it is a one-byte string, construct
6922 bytes object directly. */
6923 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6924 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6925 PyUnicode_GET_LENGTH(unicode));
6926 /* Non-Latin-1 characters present. Defer to above function to
6927 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006928 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006929}
6930
6931PyObject*
6932PyUnicode_AsLatin1String(PyObject *unicode)
6933{
6934 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006935}
6936
6937/* --- 7-bit ASCII Codec -------------------------------------------------- */
6938
Alexander Belopolsky40018472011-02-26 01:02:56 +00006939PyObject *
6940PyUnicode_DecodeASCII(const char *s,
6941 Py_ssize_t size,
6942 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006943{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006944 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006945 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006946 int kind;
6947 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006948 Py_ssize_t startinpos;
6949 Py_ssize_t endinpos;
6950 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006951 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006952 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006953 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006954 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006955
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006957 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006958
Guido van Rossumd57fd912000-03-10 22:53:23 +00006959 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006960 if (size == 1 && (unsigned char)s[0] < 128)
6961 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006962
Victor Stinner8f674cc2013-04-17 23:02:17 +02006963 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006964 writer.min_length = size;
6965 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006966 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006967
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006968 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006969 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006970 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006971 writer.pos = outpos;
6972 if (writer.pos == size)
6973 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006974
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006975 s += writer.pos;
6976 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006977 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006978 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006980 PyUnicode_WRITE(kind, data, writer.pos, c);
6981 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006982 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006985
6986 /* byte outsize range 0x00..0x7f: call the error handler */
6987
6988 if (error_handler == _Py_ERROR_UNKNOWN)
6989 error_handler = get_error_handler(errors);
6990
6991 switch (error_handler)
6992 {
6993 case _Py_ERROR_REPLACE:
6994 case _Py_ERROR_SURROGATEESCAPE:
6995 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006996 but we may switch to UCS2 at the first write */
6997 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6998 goto onError;
6999 kind = writer.kind;
7000 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007001
7002 if (error_handler == _Py_ERROR_REPLACE)
7003 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7004 else
7005 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7006 writer.pos++;
7007 ++s;
7008 break;
7009
7010 case _Py_ERROR_IGNORE:
7011 ++s;
7012 break;
7013
7014 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007015 startinpos = s-starts;
7016 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007017 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007018 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007019 "ascii", "ordinal not in range(128)",
7020 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007021 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007023 kind = writer.kind;
7024 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007026 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007027 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007028 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007029 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007030
Benjamin Peterson29060642009-01-31 22:14:21 +00007031 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007032 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007033 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007034 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007035 return NULL;
7036}
7037
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007038/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007039PyObject *
7040PyUnicode_EncodeASCII(const Py_UNICODE *p,
7041 Py_ssize_t size,
7042 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007043{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007044 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007045 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007046 if (unicode == NULL)
7047 return NULL;
7048 result = unicode_encode_ucs1(unicode, errors, 128);
7049 Py_DECREF(unicode);
7050 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007051}
7052
Alexander Belopolsky40018472011-02-26 01:02:56 +00007053PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007054_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007055{
7056 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007057 PyErr_BadArgument();
7058 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007059 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007060 if (PyUnicode_READY(unicode) == -1)
7061 return NULL;
7062 /* Fast path: if it is an ASCII-only string, construct bytes object
7063 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007064 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007065 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7066 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007067 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007068}
7069
7070PyObject *
7071PyUnicode_AsASCIIString(PyObject *unicode)
7072{
7073 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007074}
7075
Steve Dowercc16be82016-09-08 10:35:16 -07007076#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007077
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007078/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007079
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007080#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081#define NEED_RETRY
7082#endif
7083
Victor Stinner3a50e702011-10-18 21:21:00 +02007084#ifndef WC_ERR_INVALID_CHARS
7085# define WC_ERR_INVALID_CHARS 0x0080
7086#endif
7087
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007088static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007089code_page_name(UINT code_page, PyObject **obj)
7090{
7091 *obj = NULL;
7092 if (code_page == CP_ACP)
7093 return "mbcs";
7094 if (code_page == CP_UTF7)
7095 return "CP_UTF7";
7096 if (code_page == CP_UTF8)
7097 return "CP_UTF8";
7098
7099 *obj = PyBytes_FromFormat("cp%u", code_page);
7100 if (*obj == NULL)
7101 return NULL;
7102 return PyBytes_AS_STRING(*obj);
7103}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104
Victor Stinner3a50e702011-10-18 21:21:00 +02007105static DWORD
7106decode_code_page_flags(UINT code_page)
7107{
7108 if (code_page == CP_UTF7) {
7109 /* The CP_UTF7 decoder only supports flags=0 */
7110 return 0;
7111 }
7112 else
7113 return MB_ERR_INVALID_CHARS;
7114}
7115
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007117 * Decode a byte string from a Windows code page into unicode object in strict
7118 * mode.
7119 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007120 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7121 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007122 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007123static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007124decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007125 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 const char *in,
7127 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007128{
Miss Islington (bot)74829b72019-03-20 21:31:57 -07007129 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner24729f32011-11-10 20:31:37 +01007130 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007131 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132
7133 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007134 assert(insize > 0);
Miss Islington (bot)74829b72019-03-20 21:31:57 -07007135 while ((outsize = MultiByteToWideChar(code_page, flags,
7136 in, insize, NULL, 0)) <= 0)
7137 {
7138 if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7139 goto error;
7140 }
7141 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7142 flags = 0;
7143 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007144
7145 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007146 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007147 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007148 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007149 if (*v == NULL)
7150 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007152 }
7153 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007154 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007156 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007157 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007159 }
7160
7161 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7163 if (outsize <= 0)
7164 goto error;
7165 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007166
Victor Stinner3a50e702011-10-18 21:21:00 +02007167error:
7168 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7169 return -2;
7170 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007171 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007172}
7173
Victor Stinner3a50e702011-10-18 21:21:00 +02007174/*
7175 * Decode a byte string from a code page into unicode object with an error
7176 * handler.
7177 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007178 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 * UnicodeDecodeError exception and returns -1 on error.
7180 */
7181static int
7182decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007183 PyObject **v,
7184 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007185 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007186{
7187 const char *startin = in;
7188 const char *endin = in + size;
Miss Islington (bot)74829b72019-03-20 21:31:57 -07007189 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 /* Ideally, we should get reason from FormatMessage. This is the Windows
7191 2000 English version of the message. */
7192 const char *reason = "No mapping for the Unicode character exists "
7193 "in the target code page.";
7194 /* each step cannot decode more than 1 character, but a character can be
7195 represented as a surrogate pair */
Miss Islington (bot)bdeb56c2018-12-03 01:09:11 -08007196 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007197 int insize;
7198 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 PyObject *errorHandler = NULL;
7200 PyObject *exc = NULL;
7201 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007202 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007203 DWORD err;
7204 int ret = -1;
7205
7206 assert(size > 0);
7207
7208 encoding = code_page_name(code_page, &encoding_obj);
7209 if (encoding == NULL)
7210 return -1;
7211
Victor Stinner7d00cc12014-03-17 23:08:06 +01007212 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7214 UnicodeDecodeError. */
7215 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7216 if (exc != NULL) {
7217 PyCodec_StrictErrors(exc);
7218 Py_CLEAR(exc);
7219 }
7220 goto error;
7221 }
7222
7223 if (*v == NULL) {
7224 /* Create unicode object */
7225 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7226 PyErr_NoMemory();
7227 goto error;
7228 }
Victor Stinnerab595942011-12-17 04:59:06 +01007229 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007230 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 if (*v == NULL)
7232 goto error;
Miss Islington (bot)bdeb56c2018-12-03 01:09:11 -08007233 out = PyUnicode_AS_UNICODE(*v);
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 }
7235 else {
7236 /* Extend unicode object */
7237 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7238 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7239 PyErr_NoMemory();
7240 goto error;
7241 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007242 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 goto error;
Miss Islington (bot)bdeb56c2018-12-03 01:09:11 -08007244 out = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 }
7246
7247 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 while (in < endin)
7249 {
7250 /* Decode a character */
7251 insize = 1;
7252 do
7253 {
7254 outsize = MultiByteToWideChar(code_page, flags,
7255 in, insize,
7256 buffer, Py_ARRAY_LENGTH(buffer));
7257 if (outsize > 0)
7258 break;
7259 err = GetLastError();
Miss Islington (bot)74829b72019-03-20 21:31:57 -07007260 if (err == ERROR_INVALID_FLAGS && flags) {
7261 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7262 flags = 0;
7263 continue;
7264 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 if (err != ERROR_NO_UNICODE_TRANSLATION
7266 && err != ERROR_INSUFFICIENT_BUFFER)
7267 {
7268 PyErr_SetFromWindowsErr(0);
7269 goto error;
7270 }
7271 insize++;
7272 }
7273 /* 4=maximum length of a UTF-8 sequence */
7274 while (insize <= 4 && (in + insize) <= endin);
7275
7276 if (outsize <= 0) {
7277 Py_ssize_t startinpos, endinpos, outpos;
7278
Victor Stinner7d00cc12014-03-17 23:08:06 +01007279 /* last character in partial decode? */
7280 if (in + insize >= endin && !final)
7281 break;
7282
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 startinpos = in - startin;
7284 endinpos = startinpos + 1;
7285 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007286 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007287 errors, &errorHandler,
7288 encoding, reason,
7289 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007290 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 {
7292 goto error;
7293 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007294 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007295 }
7296 else {
7297 in += insize;
7298 memcpy(out, buffer, outsize * sizeof(wchar_t));
7299 out += outsize;
7300 }
7301 }
7302
7303 /* write a NUL character at the end */
7304 *out = 0;
7305
7306 /* Extend unicode object */
Miss Islington (bot)bdeb56c2018-12-03 01:09:11 -08007307 outsize = out - PyUnicode_AS_UNICODE(*v);
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007309 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007310 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007311 /* (in - startin) <= size and size is an int */
7312 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007313
7314error:
7315 Py_XDECREF(encoding_obj);
7316 Py_XDECREF(errorHandler);
7317 Py_XDECREF(exc);
7318 return ret;
7319}
7320
Victor Stinner3a50e702011-10-18 21:21:00 +02007321static PyObject *
7322decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007323 const char *s, Py_ssize_t size,
7324 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007325{
Victor Stinner76a31a62011-11-04 00:05:13 +01007326 PyObject *v = NULL;
7327 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007328
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 if (code_page < 0) {
7330 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7331 return NULL;
7332 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007333 if (size < 0) {
7334 PyErr_BadInternalCall();
7335 return NULL;
7336 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007337
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007338 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007339 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007340
Victor Stinner76a31a62011-11-04 00:05:13 +01007341 do
7342 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007343#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007344 if (size > INT_MAX) {
7345 chunk_size = INT_MAX;
7346 final = 0;
7347 done = 0;
7348 }
7349 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007350#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007351 {
7352 chunk_size = (int)size;
7353 final = (consumed == NULL);
7354 done = 1;
7355 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356
Victor Stinner76a31a62011-11-04 00:05:13 +01007357 if (chunk_size == 0 && done) {
7358 if (v != NULL)
7359 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007360 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007361 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007362
Victor Stinner76a31a62011-11-04 00:05:13 +01007363 converted = decode_code_page_strict(code_page, &v,
7364 s, chunk_size);
7365 if (converted == -2)
7366 converted = decode_code_page_errors(code_page, &v,
7367 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007368 errors, final);
7369 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007370
7371 if (converted < 0) {
7372 Py_XDECREF(v);
7373 return NULL;
7374 }
7375
7376 if (consumed)
7377 *consumed += converted;
7378
7379 s += converted;
7380 size -= converted;
7381 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007382
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007383 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007384}
7385
Alexander Belopolsky40018472011-02-26 01:02:56 +00007386PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007387PyUnicode_DecodeCodePageStateful(int code_page,
7388 const char *s,
7389 Py_ssize_t size,
7390 const char *errors,
7391 Py_ssize_t *consumed)
7392{
7393 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7394}
7395
7396PyObject *
7397PyUnicode_DecodeMBCSStateful(const char *s,
7398 Py_ssize_t size,
7399 const char *errors,
7400 Py_ssize_t *consumed)
7401{
7402 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7403}
7404
7405PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007406PyUnicode_DecodeMBCS(const char *s,
7407 Py_ssize_t size,
7408 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007409{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007410 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7411}
7412
Victor Stinner3a50e702011-10-18 21:21:00 +02007413static DWORD
7414encode_code_page_flags(UINT code_page, const char *errors)
7415{
7416 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007417 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 }
7419 else if (code_page == CP_UTF7) {
7420 /* CP_UTF7 only supports flags=0 */
7421 return 0;
7422 }
7423 else {
7424 if (errors != NULL && strcmp(errors, "replace") == 0)
7425 return 0;
7426 else
7427 return WC_NO_BEST_FIT_CHARS;
7428 }
7429}
7430
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007431/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 * Encode a Unicode string to a Windows code page into a byte string in strict
7433 * mode.
7434 *
7435 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007436 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007437 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007438static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007439encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007440 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007441 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007442{
Victor Stinner554f3f02010-06-16 23:33:54 +00007443 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 BOOL *pusedDefaultChar = &usedDefaultChar;
7445 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007446 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 const DWORD flags = encode_code_page_flags(code_page, NULL);
7449 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 /* Create a substring so that we can get the UTF-16 representation
7451 of just the slice under consideration. */
7452 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007453
Martin v. Löwis3d325192011-11-04 18:23:06 +01007454 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007455
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007457 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007459 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007460
Victor Stinner2fc507f2011-11-04 20:06:39 +01007461 substring = PyUnicode_Substring(unicode, offset, offset+len);
7462 if (substring == NULL)
7463 return -1;
7464 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7465 if (p == NULL) {
7466 Py_DECREF(substring);
7467 return -1;
7468 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007469 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007470
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007471 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007473 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 NULL, 0,
7475 NULL, pusedDefaultChar);
7476 if (outsize <= 0)
7477 goto error;
7478 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007479 if (pusedDefaultChar && *pusedDefaultChar) {
7480 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007482 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007483
Victor Stinner3a50e702011-10-18 21:21:00 +02007484 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007485 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007487 if (*outbytes == NULL) {
7488 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007489 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007490 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007492 }
7493 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007494 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007495 const Py_ssize_t n = PyBytes_Size(*outbytes);
7496 if (outsize > PY_SSIZE_T_MAX - n) {
7497 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007498 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007501 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7502 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007503 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007504 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007506 }
7507
7508 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007510 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 out, outsize,
7512 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007513 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007514 if (outsize <= 0)
7515 goto error;
7516 if (pusedDefaultChar && *pusedDefaultChar)
7517 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007518 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007519
Victor Stinner3a50e702011-10-18 21:21:00 +02007520error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007521 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007522 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7523 return -2;
7524 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007525 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007526}
7527
Victor Stinner3a50e702011-10-18 21:21:00 +02007528/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007529 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007530 * error handler.
7531 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007532 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007533 * -1 on other error.
7534 */
7535static int
7536encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007537 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007538 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007539{
Victor Stinner3a50e702011-10-18 21:21:00 +02007540 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007541 Py_ssize_t pos = unicode_offset;
7542 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007543 /* Ideally, we should get reason from FormatMessage. This is the Windows
7544 2000 English version of the message. */
7545 const char *reason = "invalid character";
7546 /* 4=maximum length of a UTF-8 sequence */
7547 char buffer[4];
7548 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7549 Py_ssize_t outsize;
7550 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007551 PyObject *errorHandler = NULL;
7552 PyObject *exc = NULL;
7553 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007554 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007555 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007556 PyObject *rep;
7557 int ret = -1;
7558
7559 assert(insize > 0);
7560
7561 encoding = code_page_name(code_page, &encoding_obj);
7562 if (encoding == NULL)
7563 return -1;
7564
7565 if (errors == NULL || strcmp(errors, "strict") == 0) {
7566 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7567 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007568 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 if (exc != NULL) {
7570 PyCodec_StrictErrors(exc);
7571 Py_DECREF(exc);
7572 }
7573 Py_XDECREF(encoding_obj);
7574 return -1;
7575 }
7576
7577 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7578 pusedDefaultChar = &usedDefaultChar;
7579 else
7580 pusedDefaultChar = NULL;
7581
7582 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7583 PyErr_NoMemory();
7584 goto error;
7585 }
7586 outsize = insize * Py_ARRAY_LENGTH(buffer);
7587
7588 if (*outbytes == NULL) {
7589 /* Create string object */
7590 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7591 if (*outbytes == NULL)
7592 goto error;
7593 out = PyBytes_AS_STRING(*outbytes);
7594 }
7595 else {
7596 /* Extend string object */
7597 Py_ssize_t n = PyBytes_Size(*outbytes);
7598 if (n > PY_SSIZE_T_MAX - outsize) {
7599 PyErr_NoMemory();
7600 goto error;
7601 }
7602 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7603 goto error;
7604 out = PyBytes_AS_STRING(*outbytes) + n;
7605 }
7606
7607 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007608 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007609 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007610 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7611 wchar_t chars[2];
7612 int charsize;
7613 if (ch < 0x10000) {
7614 chars[0] = (wchar_t)ch;
7615 charsize = 1;
7616 }
7617 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007618 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7619 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007620 charsize = 2;
7621 }
7622
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007624 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007625 buffer, Py_ARRAY_LENGTH(buffer),
7626 NULL, pusedDefaultChar);
7627 if (outsize > 0) {
7628 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7629 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007630 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007631 memcpy(out, buffer, outsize);
7632 out += outsize;
7633 continue;
7634 }
7635 }
7636 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7637 PyErr_SetFromWindowsErr(0);
7638 goto error;
7639 }
7640
Victor Stinner3a50e702011-10-18 21:21:00 +02007641 rep = unicode_encode_call_errorhandler(
7642 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007643 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007644 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007645 if (rep == NULL)
7646 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007647 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007648
7649 if (PyBytes_Check(rep)) {
7650 outsize = PyBytes_GET_SIZE(rep);
7651 if (outsize != 1) {
7652 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7653 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7654 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7655 Py_DECREF(rep);
7656 goto error;
7657 }
7658 out = PyBytes_AS_STRING(*outbytes) + offset;
7659 }
7660 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7661 out += outsize;
7662 }
7663 else {
7664 Py_ssize_t i;
7665 enum PyUnicode_Kind kind;
7666 void *data;
7667
Benjamin Petersonbac79492012-01-14 13:34:47 -05007668 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 Py_DECREF(rep);
7670 goto error;
7671 }
7672
7673 outsize = PyUnicode_GET_LENGTH(rep);
7674 if (outsize != 1) {
7675 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7676 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7677 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7678 Py_DECREF(rep);
7679 goto error;
7680 }
7681 out = PyBytes_AS_STRING(*outbytes) + offset;
7682 }
7683 kind = PyUnicode_KIND(rep);
7684 data = PyUnicode_DATA(rep);
7685 for (i=0; i < outsize; i++) {
7686 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7687 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007688 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007689 encoding, unicode,
7690 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007691 "unable to encode error handler result to ASCII");
7692 Py_DECREF(rep);
7693 goto error;
7694 }
7695 *out = (unsigned char)ch;
7696 out++;
7697 }
7698 }
7699 Py_DECREF(rep);
7700 }
7701 /* write a NUL byte */
7702 *out = 0;
7703 outsize = out - PyBytes_AS_STRING(*outbytes);
7704 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7705 if (_PyBytes_Resize(outbytes, outsize) < 0)
7706 goto error;
7707 ret = 0;
7708
7709error:
7710 Py_XDECREF(encoding_obj);
7711 Py_XDECREF(errorHandler);
7712 Py_XDECREF(exc);
7713 return ret;
7714}
7715
Victor Stinner3a50e702011-10-18 21:21:00 +02007716static PyObject *
7717encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007718 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007719 const char *errors)
7720{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007721 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007722 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007723 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007724 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007725
Victor Stinner29dacf22015-01-26 16:41:32 +01007726 if (!PyUnicode_Check(unicode)) {
7727 PyErr_BadArgument();
7728 return NULL;
7729 }
7730
Benjamin Petersonbac79492012-01-14 13:34:47 -05007731 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007732 return NULL;
7733 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007734
Victor Stinner3a50e702011-10-18 21:21:00 +02007735 if (code_page < 0) {
7736 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7737 return NULL;
7738 }
7739
Martin v. Löwis3d325192011-11-04 18:23:06 +01007740 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007741 return PyBytes_FromStringAndSize(NULL, 0);
7742
Victor Stinner7581cef2011-11-03 22:32:33 +01007743 offset = 0;
7744 do
7745 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007746#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007747 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007748 chunks. */
7749 if (len > INT_MAX/2) {
7750 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007751 done = 0;
7752 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007753 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007754#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007755 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007756 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007757 done = 1;
7758 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007759
Victor Stinner76a31a62011-11-04 00:05:13 +01007760 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007761 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007762 errors);
7763 if (ret == -2)
7764 ret = encode_code_page_errors(code_page, &outbytes,
7765 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007766 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007767 if (ret < 0) {
7768 Py_XDECREF(outbytes);
7769 return NULL;
7770 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007771
Victor Stinner7581cef2011-11-03 22:32:33 +01007772 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007773 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007774 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007775
Victor Stinner3a50e702011-10-18 21:21:00 +02007776 return outbytes;
7777}
7778
7779PyObject *
7780PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7781 Py_ssize_t size,
7782 const char *errors)
7783{
Victor Stinner7581cef2011-11-03 22:32:33 +01007784 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007785 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007786 if (unicode == NULL)
7787 return NULL;
7788 res = encode_code_page(CP_ACP, unicode, errors);
7789 Py_DECREF(unicode);
7790 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007791}
7792
7793PyObject *
7794PyUnicode_EncodeCodePage(int code_page,
7795 PyObject *unicode,
7796 const char *errors)
7797{
Victor Stinner7581cef2011-11-03 22:32:33 +01007798 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007799}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007800
Alexander Belopolsky40018472011-02-26 01:02:56 +00007801PyObject *
7802PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007803{
Victor Stinner7581cef2011-11-03 22:32:33 +01007804 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007805}
7806
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007807#undef NEED_RETRY
7808
Steve Dowercc16be82016-09-08 10:35:16 -07007809#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007810
Guido van Rossumd57fd912000-03-10 22:53:23 +00007811/* --- Character Mapping Codec -------------------------------------------- */
7812
Victor Stinnerfb161b12013-04-18 01:44:27 +02007813static int
7814charmap_decode_string(const char *s,
7815 Py_ssize_t size,
7816 PyObject *mapping,
7817 const char *errors,
7818 _PyUnicodeWriter *writer)
7819{
7820 const char *starts = s;
7821 const char *e;
7822 Py_ssize_t startinpos, endinpos;
7823 PyObject *errorHandler = NULL, *exc = NULL;
7824 Py_ssize_t maplen;
7825 enum PyUnicode_Kind mapkind;
7826 void *mapdata;
7827 Py_UCS4 x;
7828 unsigned char ch;
7829
7830 if (PyUnicode_READY(mapping) == -1)
7831 return -1;
7832
7833 maplen = PyUnicode_GET_LENGTH(mapping);
7834 mapdata = PyUnicode_DATA(mapping);
7835 mapkind = PyUnicode_KIND(mapping);
7836
7837 e = s + size;
7838
7839 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7840 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7841 * is disabled in encoding aliases, latin1 is preferred because
7842 * its implementation is faster. */
7843 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7844 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7845 Py_UCS4 maxchar = writer->maxchar;
7846
7847 assert (writer->kind == PyUnicode_1BYTE_KIND);
7848 while (s < e) {
7849 ch = *s;
7850 x = mapdata_ucs1[ch];
7851 if (x > maxchar) {
7852 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7853 goto onError;
7854 maxchar = writer->maxchar;
7855 outdata = (Py_UCS1 *)writer->data;
7856 }
7857 outdata[writer->pos] = x;
7858 writer->pos++;
7859 ++s;
7860 }
7861 return 0;
7862 }
7863
7864 while (s < e) {
7865 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7866 enum PyUnicode_Kind outkind = writer->kind;
7867 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7868 if (outkind == PyUnicode_1BYTE_KIND) {
7869 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7870 Py_UCS4 maxchar = writer->maxchar;
7871 while (s < e) {
7872 ch = *s;
7873 x = mapdata_ucs2[ch];
7874 if (x > maxchar)
7875 goto Error;
7876 outdata[writer->pos] = x;
7877 writer->pos++;
7878 ++s;
7879 }
7880 break;
7881 }
7882 else if (outkind == PyUnicode_2BYTE_KIND) {
7883 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7884 while (s < e) {
7885 ch = *s;
7886 x = mapdata_ucs2[ch];
7887 if (x == 0xFFFE)
7888 goto Error;
7889 outdata[writer->pos] = x;
7890 writer->pos++;
7891 ++s;
7892 }
7893 break;
7894 }
7895 }
7896 ch = *s;
7897
7898 if (ch < maplen)
7899 x = PyUnicode_READ(mapkind, mapdata, ch);
7900 else
7901 x = 0xfffe; /* invalid value */
7902Error:
7903 if (x == 0xfffe)
7904 {
7905 /* undefined mapping */
7906 startinpos = s-starts;
7907 endinpos = startinpos+1;
7908 if (unicode_decode_call_errorhandler_writer(
7909 errors, &errorHandler,
7910 "charmap", "character maps to <undefined>",
7911 &starts, &e, &startinpos, &endinpos, &exc, &s,
7912 writer)) {
7913 goto onError;
7914 }
7915 continue;
7916 }
7917
7918 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7919 goto onError;
7920 ++s;
7921 }
7922 Py_XDECREF(errorHandler);
7923 Py_XDECREF(exc);
7924 return 0;
7925
7926onError:
7927 Py_XDECREF(errorHandler);
7928 Py_XDECREF(exc);
7929 return -1;
7930}
7931
7932static int
7933charmap_decode_mapping(const char *s,
7934 Py_ssize_t size,
7935 PyObject *mapping,
7936 const char *errors,
7937 _PyUnicodeWriter *writer)
7938{
7939 const char *starts = s;
7940 const char *e;
7941 Py_ssize_t startinpos, endinpos;
7942 PyObject *errorHandler = NULL, *exc = NULL;
7943 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007944 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007945
7946 e = s + size;
7947
7948 while (s < e) {
7949 ch = *s;
7950
7951 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7952 key = PyLong_FromLong((long)ch);
7953 if (key == NULL)
7954 goto onError;
7955
7956 item = PyObject_GetItem(mapping, key);
7957 Py_DECREF(key);
7958 if (item == NULL) {
7959 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7960 /* No mapping found means: mapping is undefined. */
7961 PyErr_Clear();
7962 goto Undefined;
7963 } else
7964 goto onError;
7965 }
7966
7967 /* Apply mapping */
7968 if (item == Py_None)
7969 goto Undefined;
7970 if (PyLong_Check(item)) {
7971 long value = PyLong_AS_LONG(item);
7972 if (value == 0xFFFE)
7973 goto Undefined;
7974 if (value < 0 || value > MAX_UNICODE) {
7975 PyErr_Format(PyExc_TypeError,
7976 "character mapping must be in range(0x%lx)",
7977 (unsigned long)MAX_UNICODE + 1);
7978 goto onError;
7979 }
7980
7981 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7982 goto onError;
7983 }
7984 else if (PyUnicode_Check(item)) {
7985 if (PyUnicode_READY(item) == -1)
7986 goto onError;
7987 if (PyUnicode_GET_LENGTH(item) == 1) {
7988 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7989 if (value == 0xFFFE)
7990 goto Undefined;
7991 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7992 goto onError;
7993 }
7994 else {
7995 writer->overallocate = 1;
7996 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7997 goto onError;
7998 }
7999 }
8000 else {
8001 /* wrong return value */
8002 PyErr_SetString(PyExc_TypeError,
8003 "character mapping must return integer, None or str");
8004 goto onError;
8005 }
8006 Py_CLEAR(item);
8007 ++s;
8008 continue;
8009
8010Undefined:
8011 /* undefined mapping */
8012 Py_CLEAR(item);
8013 startinpos = s-starts;
8014 endinpos = startinpos+1;
8015 if (unicode_decode_call_errorhandler_writer(
8016 errors, &errorHandler,
8017 "charmap", "character maps to <undefined>",
8018 &starts, &e, &startinpos, &endinpos, &exc, &s,
8019 writer)) {
8020 goto onError;
8021 }
8022 }
8023 Py_XDECREF(errorHandler);
8024 Py_XDECREF(exc);
8025 return 0;
8026
8027onError:
8028 Py_XDECREF(item);
8029 Py_XDECREF(errorHandler);
8030 Py_XDECREF(exc);
8031 return -1;
8032}
8033
Alexander Belopolsky40018472011-02-26 01:02:56 +00008034PyObject *
8035PyUnicode_DecodeCharmap(const char *s,
8036 Py_ssize_t size,
8037 PyObject *mapping,
8038 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008039{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008040 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008041
Guido van Rossumd57fd912000-03-10 22:53:23 +00008042 /* Default to Latin-1 */
8043 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008045
Guido van Rossumd57fd912000-03-10 22:53:23 +00008046 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008047 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008048 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008049 writer.min_length = size;
8050 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008051 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008052
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008053 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008054 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8055 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008056 }
8057 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008058 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8059 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008060 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008061 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008062
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008064 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008065 return NULL;
8066}
8067
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008068/* Charmap encoding: the lookup table */
8069
Alexander Belopolsky40018472011-02-26 01:02:56 +00008070struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 PyObject_HEAD
8072 unsigned char level1[32];
8073 int count2, count3;
8074 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008075};
8076
8077static PyObject*
8078encoding_map_size(PyObject *obj, PyObject* args)
8079{
8080 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008081 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008082 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083}
8084
8085static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008086 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 PyDoc_STR("Return the size (in bytes) of this object") },
8088 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089};
8090
8091static void
8092encoding_map_dealloc(PyObject* o)
8093{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008094 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095}
8096
8097static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008098 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008099 "EncodingMap", /*tp_name*/
8100 sizeof(struct encoding_map), /*tp_basicsize*/
8101 0, /*tp_itemsize*/
8102 /* methods */
8103 encoding_map_dealloc, /*tp_dealloc*/
8104 0, /*tp_print*/
8105 0, /*tp_getattr*/
8106 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008107 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008108 0, /*tp_repr*/
8109 0, /*tp_as_number*/
8110 0, /*tp_as_sequence*/
8111 0, /*tp_as_mapping*/
8112 0, /*tp_hash*/
8113 0, /*tp_call*/
8114 0, /*tp_str*/
8115 0, /*tp_getattro*/
8116 0, /*tp_setattro*/
8117 0, /*tp_as_buffer*/
8118 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8119 0, /*tp_doc*/
8120 0, /*tp_traverse*/
8121 0, /*tp_clear*/
8122 0, /*tp_richcompare*/
8123 0, /*tp_weaklistoffset*/
8124 0, /*tp_iter*/
8125 0, /*tp_iternext*/
8126 encoding_map_methods, /*tp_methods*/
8127 0, /*tp_members*/
8128 0, /*tp_getset*/
8129 0, /*tp_base*/
8130 0, /*tp_dict*/
8131 0, /*tp_descr_get*/
8132 0, /*tp_descr_set*/
8133 0, /*tp_dictoffset*/
8134 0, /*tp_init*/
8135 0, /*tp_alloc*/
8136 0, /*tp_new*/
8137 0, /*tp_free*/
8138 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008139};
8140
8141PyObject*
8142PyUnicode_BuildEncodingMap(PyObject* string)
8143{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 PyObject *result;
8145 struct encoding_map *mresult;
8146 int i;
8147 int need_dict = 0;
8148 unsigned char level1[32];
8149 unsigned char level2[512];
8150 unsigned char *mlevel1, *mlevel2, *mlevel3;
8151 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008152 int kind;
8153 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008154 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008155 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008157 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008158 PyErr_BadArgument();
8159 return NULL;
8160 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008161 kind = PyUnicode_KIND(string);
8162 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008163 length = PyUnicode_GET_LENGTH(string);
8164 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008165 memset(level1, 0xFF, sizeof level1);
8166 memset(level2, 0xFF, sizeof level2);
8167
8168 /* If there isn't a one-to-one mapping of NULL to \0,
8169 or if there are non-BMP characters, we need to use
8170 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008171 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008172 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008173 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008174 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008175 ch = PyUnicode_READ(kind, data, i);
8176 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008177 need_dict = 1;
8178 break;
8179 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008180 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008181 /* unmapped character */
8182 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008183 l1 = ch >> 11;
8184 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008185 if (level1[l1] == 0xFF)
8186 level1[l1] = count2++;
8187 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008188 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008189 }
8190
8191 if (count2 >= 0xFF || count3 >= 0xFF)
8192 need_dict = 1;
8193
8194 if (need_dict) {
8195 PyObject *result = PyDict_New();
8196 PyObject *key, *value;
8197 if (!result)
8198 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008199 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008200 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008201 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008202 if (!key || !value)
8203 goto failed1;
8204 if (PyDict_SetItem(result, key, value) == -1)
8205 goto failed1;
8206 Py_DECREF(key);
8207 Py_DECREF(value);
8208 }
8209 return result;
8210 failed1:
8211 Py_XDECREF(key);
8212 Py_XDECREF(value);
8213 Py_DECREF(result);
8214 return NULL;
8215 }
8216
8217 /* Create a three-level trie */
8218 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8219 16*count2 + 128*count3 - 1);
8220 if (!result)
8221 return PyErr_NoMemory();
8222 PyObject_Init(result, &EncodingMapType);
8223 mresult = (struct encoding_map*)result;
8224 mresult->count2 = count2;
8225 mresult->count3 = count3;
8226 mlevel1 = mresult->level1;
8227 mlevel2 = mresult->level23;
8228 mlevel3 = mresult->level23 + 16*count2;
8229 memcpy(mlevel1, level1, 32);
8230 memset(mlevel2, 0xFF, 16*count2);
8231 memset(mlevel3, 0, 128*count3);
8232 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008233 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008234 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008235 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8236 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008237 /* unmapped character */
8238 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008239 o1 = ch>>11;
8240 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008241 i2 = 16*mlevel1[o1] + o2;
8242 if (mlevel2[i2] == 0xFF)
8243 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008244 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008245 i3 = 128*mlevel2[i2] + o3;
8246 mlevel3[i3] = i;
8247 }
8248 return result;
8249}
8250
8251static int
Victor Stinner22168992011-11-20 17:09:18 +01008252encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008253{
8254 struct encoding_map *map = (struct encoding_map*)mapping;
8255 int l1 = c>>11;
8256 int l2 = (c>>7) & 0xF;
8257 int l3 = c & 0x7F;
8258 int i;
8259
Victor Stinner22168992011-11-20 17:09:18 +01008260 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008262 if (c == 0)
8263 return 0;
8264 /* level 1*/
8265 i = map->level1[l1];
8266 if (i == 0xFF) {
8267 return -1;
8268 }
8269 /* level 2*/
8270 i = map->level23[16*i+l2];
8271 if (i == 0xFF) {
8272 return -1;
8273 }
8274 /* level 3 */
8275 i = map->level23[16*map->count2 + 128*i + l3];
8276 if (i == 0) {
8277 return -1;
8278 }
8279 return i;
8280}
8281
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282/* Lookup the character ch in the mapping. If the character
8283 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008284 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008285static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008286charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287{
Christian Heimes217cfd12007-12-02 14:31:20 +00008288 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289 PyObject *x;
8290
8291 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 x = PyObject_GetItem(mapping, w);
8294 Py_DECREF(w);
8295 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8297 /* No mapping found means: mapping is undefined. */
8298 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008299 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 } else
8301 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008302 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008303 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008305 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 long value = PyLong_AS_LONG(x);
8307 if (value < 0 || value > 255) {
8308 PyErr_SetString(PyExc_TypeError,
8309 "character mapping must be in range(256)");
8310 Py_DECREF(x);
8311 return NULL;
8312 }
8313 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008314 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008315 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008317 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 /* wrong return value */
8319 PyErr_Format(PyExc_TypeError,
8320 "character mapping must return integer, bytes or None, not %.400s",
8321 x->ob_type->tp_name);
8322 Py_DECREF(x);
8323 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324 }
8325}
8326
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008327static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008328charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008329{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008330 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8331 /* exponentially overallocate to minimize reallocations */
8332 if (requiredsize < 2*outsize)
8333 requiredsize = 2*outsize;
8334 if (_PyBytes_Resize(outobj, requiredsize))
8335 return -1;
8336 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008337}
8338
Benjamin Peterson14339b62009-01-31 16:36:08 +00008339typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008341} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008343 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 space is available. Return a new reference to the object that
8345 was put in the output buffer, or Py_None, if the mapping was undefined
8346 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008347 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008348static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008349charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008350 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008352 PyObject *rep;
8353 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008354 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355
Christian Heimes90aa7642007-12-19 02:45:37 +00008356 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008357 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008359 if (res == -1)
8360 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 if (outsize<requiredsize)
8362 if (charmapencode_resize(outobj, outpos, requiredsize))
8363 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008364 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 outstart[(*outpos)++] = (char)res;
8366 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008367 }
8368
8369 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008372 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 Py_DECREF(rep);
8374 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008375 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 if (PyLong_Check(rep)) {
8377 Py_ssize_t requiredsize = *outpos+1;
8378 if (outsize<requiredsize)
8379 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8380 Py_DECREF(rep);
8381 return enc_EXCEPTION;
8382 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008383 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008385 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 else {
8387 const char *repchars = PyBytes_AS_STRING(rep);
8388 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8389 Py_ssize_t requiredsize = *outpos+repsize;
8390 if (outsize<requiredsize)
8391 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8392 Py_DECREF(rep);
8393 return enc_EXCEPTION;
8394 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008395 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 memcpy(outstart + *outpos, repchars, repsize);
8397 *outpos += repsize;
8398 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008400 Py_DECREF(rep);
8401 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402}
8403
8404/* handle an error in PyUnicode_EncodeCharmap
8405 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008406static int
8407charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008410 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008411 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412{
8413 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008414 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008415 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008416 enum PyUnicode_Kind kind;
8417 void *data;
8418 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008420 Py_ssize_t collstartpos = *inpos;
8421 Py_ssize_t collendpos = *inpos+1;
8422 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008423 const char *encoding = "charmap";
8424 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008425 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008426 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008427 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428
Benjamin Petersonbac79492012-01-14 13:34:47 -05008429 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008430 return -1;
8431 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432 /* find all unencodable characters */
8433 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008434 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008435 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008436 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008437 val = encoding_map_lookup(ch, mapping);
8438 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 break;
8440 ++collendpos;
8441 continue;
8442 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008443
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008444 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8445 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 if (rep==NULL)
8447 return -1;
8448 else if (rep!=Py_None) {
8449 Py_DECREF(rep);
8450 break;
8451 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008452 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454 }
8455 /* cache callback name lookup
8456 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008457 if (*error_handler == _Py_ERROR_UNKNOWN)
8458 *error_handler = get_error_handler(errors);
8459
8460 switch (*error_handler) {
8461 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008462 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008463 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008464
8465 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008466 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 x = charmapencode_output('?', mapping, res, respos);
8468 if (x==enc_EXCEPTION) {
8469 return -1;
8470 }
8471 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008472 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 return -1;
8474 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008475 }
8476 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008477 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008478 *inpos = collendpos;
8479 break;
Victor Stinner50149202015-09-22 00:26:54 +02008480
8481 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008482 /* generate replacement (temporarily (mis)uses p) */
8483 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 char buffer[2+29+1+1];
8485 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008486 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 for (cp = buffer; *cp; ++cp) {
8488 x = charmapencode_output(*cp, mapping, res, respos);
8489 if (x==enc_EXCEPTION)
8490 return -1;
8491 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008492 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 return -1;
8494 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 }
8496 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008497 *inpos = collendpos;
8498 break;
Victor Stinner50149202015-09-22 00:26:54 +02008499
Benjamin Peterson14339b62009-01-31 16:36:08 +00008500 default:
Victor Stinner50149202015-09-22 00:26:54 +02008501 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008502 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008504 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008506 if (PyBytes_Check(repunicode)) {
8507 /* Directly copy bytes result to output. */
8508 Py_ssize_t outsize = PyBytes_Size(*res);
8509 Py_ssize_t requiredsize;
8510 repsize = PyBytes_Size(repunicode);
8511 requiredsize = *respos + repsize;
8512 if (requiredsize > outsize)
8513 /* Make room for all additional bytes. */
8514 if (charmapencode_resize(res, respos, requiredsize)) {
8515 Py_DECREF(repunicode);
8516 return -1;
8517 }
8518 memcpy(PyBytes_AsString(*res) + *respos,
8519 PyBytes_AsString(repunicode), repsize);
8520 *respos += repsize;
8521 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008522 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008523 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008524 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008525 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008526 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008527 Py_DECREF(repunicode);
8528 return -1;
8529 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008530 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008531 data = PyUnicode_DATA(repunicode);
8532 kind = PyUnicode_KIND(repunicode);
8533 for (index = 0; index < repsize; index++) {
8534 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8535 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008537 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 return -1;
8539 }
8540 else if (x==enc_FAILED) {
8541 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008542 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 return -1;
8544 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008545 }
8546 *inpos = newpos;
8547 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 }
8549 return 0;
8550}
8551
Alexander Belopolsky40018472011-02-26 01:02:56 +00008552PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008553_PyUnicode_EncodeCharmap(PyObject *unicode,
8554 PyObject *mapping,
8555 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008556{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557 /* output object */
8558 PyObject *res = NULL;
8559 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008560 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008561 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008563 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008564 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008566 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008567 void *data;
8568 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569
Benjamin Petersonbac79492012-01-14 13:34:47 -05008570 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008571 return NULL;
8572 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008573 data = PyUnicode_DATA(unicode);
8574 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008575
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576 /* Default to Latin-1 */
8577 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008578 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 /* allocate enough for a simple encoding without
8581 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008582 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 if (res == NULL)
8584 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008585 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008587
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008589 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008591 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 if (x==enc_EXCEPTION) /* error */
8593 goto onError;
8594 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008595 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008597 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 &res, &respos)) {
8599 goto onError;
8600 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008601 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 else
8603 /* done with this character => adjust input position */
8604 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008607 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008608 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008609 if (_PyBytes_Resize(&res, respos) < 0)
8610 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008611
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008613 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 return res;
8615
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 Py_XDECREF(res);
8618 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008619 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620 return NULL;
8621}
8622
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008623/* Deprecated */
8624PyObject *
8625PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8626 Py_ssize_t size,
8627 PyObject *mapping,
8628 const char *errors)
8629{
8630 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008631 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008632 if (unicode == NULL)
8633 return NULL;
8634 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8635 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008636 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008637}
8638
Alexander Belopolsky40018472011-02-26 01:02:56 +00008639PyObject *
8640PyUnicode_AsCharmapString(PyObject *unicode,
8641 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008642{
8643 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 PyErr_BadArgument();
8645 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008646 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008647 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648}
8649
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008651static void
8652make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008654 Py_ssize_t startpos, Py_ssize_t endpos,
8655 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008656{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 *exceptionObject = _PyUnicodeTranslateError_Create(
8659 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008660 }
8661 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8663 goto onError;
8664 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8665 goto onError;
8666 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8667 goto onError;
8668 return;
8669 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008670 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008671 }
8672}
8673
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674/* error handling callback helper:
8675 build arguments, call the callback and check the arguments,
8676 put the result into newpos and return the replacement string, which
8677 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008678static PyObject *
8679unicode_translate_call_errorhandler(const char *errors,
8680 PyObject **errorHandler,
8681 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008683 Py_ssize_t startpos, Py_ssize_t endpos,
8684 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008686 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008688 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689 PyObject *restuple;
8690 PyObject *resunicode;
8691
8692 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008694 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 }
8697
8698 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008700 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008702
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008703 restuple = PyObject_CallFunctionObjArgs(
8704 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008705 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008707 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008708 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008709 Py_DECREF(restuple);
8710 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008712 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 &resunicode, &i_newpos)) {
8714 Py_DECREF(restuple);
8715 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008717 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008719 else
8720 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008721 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008722 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 Py_DECREF(restuple);
8724 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008725 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008726 Py_INCREF(resunicode);
8727 Py_DECREF(restuple);
8728 return resunicode;
8729}
8730
8731/* Lookup the character ch in the mapping and put the result in result,
8732 which must be decrefed by the caller.
8733 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008734static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736{
Christian Heimes217cfd12007-12-02 14:31:20 +00008737 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 PyObject *x;
8739
8740 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008742 x = PyObject_GetItem(mapping, w);
8743 Py_DECREF(w);
8744 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8746 /* No mapping found means: use 1:1 mapping. */
8747 PyErr_Clear();
8748 *result = NULL;
8749 return 0;
8750 } else
8751 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752 }
8753 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 *result = x;
8755 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008756 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008757 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008759 if (value < 0 || value > MAX_UNICODE) {
8760 PyErr_Format(PyExc_ValueError,
8761 "character mapping must be in range(0x%x)",
8762 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008763 Py_DECREF(x);
8764 return -1;
8765 }
8766 *result = x;
8767 return 0;
8768 }
8769 else if (PyUnicode_Check(x)) {
8770 *result = x;
8771 return 0;
8772 }
8773 else {
8774 /* wrong return value */
8775 PyErr_SetString(PyExc_TypeError,
8776 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008777 Py_DECREF(x);
8778 return -1;
8779 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008780}
Victor Stinner1194ea02014-04-04 19:37:40 +02008781
8782/* lookup the character, write the result into the writer.
8783 Return 1 if the result was written into the writer, return 0 if the mapping
8784 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008785static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008786charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8787 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008788{
Victor Stinner1194ea02014-04-04 19:37:40 +02008789 PyObject *item;
8790
8791 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008792 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008793
8794 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008795 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008796 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008797 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008798 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008799 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008800 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008801
8802 if (item == Py_None) {
8803 Py_DECREF(item);
8804 return 0;
8805 }
8806
8807 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008808 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8809 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8810 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008811 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8812 Py_DECREF(item);
8813 return -1;
8814 }
8815 Py_DECREF(item);
8816 return 1;
8817 }
8818
8819 if (!PyUnicode_Check(item)) {
8820 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008822 }
8823
8824 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8825 Py_DECREF(item);
8826 return -1;
8827 }
8828
8829 Py_DECREF(item);
8830 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008831}
8832
Victor Stinner89a76ab2014-04-05 11:44:04 +02008833static int
8834unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8835 Py_UCS1 *translate)
8836{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008837 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008838 int ret = 0;
8839
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840 if (charmaptranslate_lookup(ch, mapping, &item)) {
8841 return -1;
8842 }
8843
8844 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008845 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008846 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008847 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008848 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008849 /* not found => default to 1:1 mapping */
8850 translate[ch] = ch;
8851 return 1;
8852 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008853 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008854 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008855 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8856 used it */
8857 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008858 /* invalid character or character outside ASCII:
8859 skip the fast translate */
8860 goto exit;
8861 }
8862 translate[ch] = (Py_UCS1)replace;
8863 }
8864 else if (PyUnicode_Check(item)) {
8865 Py_UCS4 replace;
8866
8867 if (PyUnicode_READY(item) == -1) {
8868 Py_DECREF(item);
8869 return -1;
8870 }
8871 if (PyUnicode_GET_LENGTH(item) != 1)
8872 goto exit;
8873
8874 replace = PyUnicode_READ_CHAR(item, 0);
8875 if (replace > 127)
8876 goto exit;
8877 translate[ch] = (Py_UCS1)replace;
8878 }
8879 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008880 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008881 goto exit;
8882 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008883 ret = 1;
8884
Benjamin Peterson1365de72014-04-07 20:15:41 -04008885 exit:
8886 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008887 return ret;
8888}
8889
8890/* Fast path for ascii => ascii translation. Return 1 if the whole string
8891 was translated into writer, return 0 if the input string was partially
8892 translated into writer, raise an exception and return -1 on error. */
8893static int
8894unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008895 _PyUnicodeWriter *writer, int ignore,
8896 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897{
Victor Stinner872b2912014-04-05 14:27:07 +02008898 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008899 Py_ssize_t len;
8900 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008901 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008902
Victor Stinner89a76ab2014-04-05 11:44:04 +02008903 len = PyUnicode_GET_LENGTH(input);
8904
Victor Stinner872b2912014-04-05 14:27:07 +02008905 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008906
8907 in = PyUnicode_1BYTE_DATA(input);
8908 end = in + len;
8909
8910 assert(PyUnicode_IS_ASCII(writer->buffer));
8911 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8912 out = PyUnicode_1BYTE_DATA(writer->buffer);
8913
Victor Stinner872b2912014-04-05 14:27:07 +02008914 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008915 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008916 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008917 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008918 int translate = unicode_fast_translate_lookup(mapping, ch,
8919 ascii_table);
8920 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008921 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008922 if (translate == 0)
8923 goto exit;
8924 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008925 }
Victor Stinner872b2912014-04-05 14:27:07 +02008926 if (ch2 == 0xfe) {
8927 if (ignore)
8928 continue;
8929 goto exit;
8930 }
8931 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008932 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008933 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008934 }
Victor Stinner872b2912014-04-05 14:27:07 +02008935 res = 1;
8936
8937exit:
8938 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008939 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008940 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008941}
8942
Victor Stinner3222da22015-10-01 22:07:32 +02008943static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008944_PyUnicode_TranslateCharmap(PyObject *input,
8945 PyObject *mapping,
8946 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008948 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008949 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950 Py_ssize_t size, i;
8951 int kind;
8952 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008953 _PyUnicodeWriter writer;
8954 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008955 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008956 PyObject *errorHandler = NULL;
8957 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008958 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008959 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008960
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008962 PyErr_BadArgument();
8963 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008964 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 if (PyUnicode_READY(input) == -1)
8967 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008968 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969 kind = PyUnicode_KIND(input);
8970 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008972 if (size == 0)
8973 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008974
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008975 /* allocate enough for a simple 1:1 translation without
8976 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008977 _PyUnicodeWriter_Init(&writer);
8978 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008979 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008980
Victor Stinner872b2912014-04-05 14:27:07 +02008981 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8982
Victor Stinner33798672016-03-01 21:59:58 +01008983 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008984 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008985 if (PyUnicode_IS_ASCII(input)) {
8986 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8987 if (res < 0) {
8988 _PyUnicodeWriter_Dealloc(&writer);
8989 return NULL;
8990 }
8991 if (res == 1)
8992 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008993 }
Victor Stinner33798672016-03-01 21:59:58 +01008994 else {
8995 i = 0;
8996 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008998 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009000 int translate;
9001 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9002 Py_ssize_t newpos;
9003 /* startpos for collecting untranslatable chars */
9004 Py_ssize_t collstart;
9005 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009006 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009007
Victor Stinner1194ea02014-04-04 19:37:40 +02009008 ch = PyUnicode_READ(kind, data, i);
9009 translate = charmaptranslate_output(ch, mapping, &writer);
9010 if (translate < 0)
9011 goto onError;
9012
9013 if (translate != 0) {
9014 /* it worked => adjust input pointer */
9015 ++i;
9016 continue;
9017 }
9018
9019 /* untranslatable character */
9020 collstart = i;
9021 collend = i+1;
9022
9023 /* find all untranslatable characters */
9024 while (collend < size) {
9025 PyObject *x;
9026 ch = PyUnicode_READ(kind, data, collend);
9027 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009028 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009029 Py_XDECREF(x);
9030 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009031 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009032 ++collend;
9033 }
9034
9035 if (ignore) {
9036 i = collend;
9037 }
9038 else {
9039 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9040 reason, input, &exc,
9041 collstart, collend, &newpos);
9042 if (repunicode == NULL)
9043 goto onError;
9044 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009045 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009046 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009047 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009048 Py_DECREF(repunicode);
9049 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009050 }
9051 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009052 Py_XDECREF(exc);
9053 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009054 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009055
Benjamin Peterson29060642009-01-31 22:14:21 +00009056 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009057 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009058 Py_XDECREF(exc);
9059 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009060 return NULL;
9061}
9062
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009063/* Deprecated. Use PyUnicode_Translate instead. */
9064PyObject *
9065PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9066 Py_ssize_t size,
9067 PyObject *mapping,
9068 const char *errors)
9069{
Christian Heimes5f520f42012-09-11 14:03:25 +02009070 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009071 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 if (!unicode)
9073 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009074 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9075 Py_DECREF(unicode);
9076 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077}
9078
Alexander Belopolsky40018472011-02-26 01:02:56 +00009079PyObject *
9080PyUnicode_Translate(PyObject *str,
9081 PyObject *mapping,
9082 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009083{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009084 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009085 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009086 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009087}
Tim Petersced69f82003-09-16 20:30:58 +00009088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089PyObject *
9090_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9091{
9092 if (!PyUnicode_Check(unicode)) {
9093 PyErr_BadInternalCall();
9094 return NULL;
9095 }
9096 if (PyUnicode_READY(unicode) == -1)
9097 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009098 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009099 /* If the string is already ASCII, just return the same string */
9100 Py_INCREF(unicode);
9101 return unicode;
9102 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009103
9104 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9105 PyObject *result = PyUnicode_New(len, 127);
9106 if (result == NULL) {
9107 return NULL;
9108 }
9109
9110 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9111 int kind = PyUnicode_KIND(unicode);
9112 const void *data = PyUnicode_DATA(unicode);
9113 Py_ssize_t i;
9114 for (i = 0; i < len; ++i) {
9115 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9116 if (ch < 127) {
9117 out[i] = ch;
9118 }
9119 else if (Py_UNICODE_ISSPACE(ch)) {
9120 out[i] = ' ';
9121 }
9122 else {
9123 int decimal = Py_UNICODE_TODECIMAL(ch);
9124 if (decimal < 0) {
9125 out[i] = '?';
Miss Islington (bot)c7214722018-07-13 20:58:12 -07009126 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009127 _PyUnicode_LENGTH(result) = i + 1;
9128 break;
9129 }
9130 out[i] = '0' + decimal;
9131 }
9132 }
9133
Miss Islington (bot)c7214722018-07-13 20:58:12 -07009134 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009135 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136}
9137
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009138PyObject *
9139PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9140 Py_ssize_t length)
9141{
Victor Stinnerf0124502011-11-21 23:12:56 +01009142 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009143 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009144 Py_UCS4 maxchar;
9145 enum PyUnicode_Kind kind;
9146 void *data;
9147
Victor Stinner99d7ad02012-02-22 13:37:39 +01009148 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009149 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009150 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009151 if (ch > 127) {
9152 int decimal = Py_UNICODE_TODECIMAL(ch);
9153 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009154 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009155 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009156 }
9157 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009158
9159 /* Copy to a new string */
9160 decimal = PyUnicode_New(length, maxchar);
9161 if (decimal == NULL)
9162 return decimal;
9163 kind = PyUnicode_KIND(decimal);
9164 data = PyUnicode_DATA(decimal);
9165 /* Iterate over code points */
9166 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009167 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009168 if (ch > 127) {
9169 int decimal = Py_UNICODE_TODECIMAL(ch);
9170 if (decimal >= 0)
9171 ch = '0' + decimal;
9172 }
9173 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009175 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009176}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009177/* --- Decimal Encoder ---------------------------------------------------- */
9178
Alexander Belopolsky40018472011-02-26 01:02:56 +00009179int
9180PyUnicode_EncodeDecimal(Py_UNICODE *s,
9181 Py_ssize_t length,
9182 char *output,
9183 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009184{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009185 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009186 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009187 enum PyUnicode_Kind kind;
9188 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009189
9190 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009191 PyErr_BadArgument();
9192 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009193 }
9194
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009195 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009196 if (unicode == NULL)
9197 return -1;
9198
Victor Stinner42bf7752011-11-21 22:52:58 +01009199 kind = PyUnicode_KIND(unicode);
9200 data = PyUnicode_DATA(unicode);
9201
Victor Stinnerb84d7232011-11-22 01:50:07 +01009202 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009203 PyObject *exc;
9204 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009205 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009206 Py_ssize_t startpos;
9207
9208 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009209
Benjamin Peterson29060642009-01-31 22:14:21 +00009210 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009211 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009212 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009213 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009214 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009215 decimal = Py_UNICODE_TODECIMAL(ch);
9216 if (decimal >= 0) {
9217 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009218 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009219 continue;
9220 }
9221 if (0 < ch && ch < 256) {
9222 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009223 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009224 continue;
9225 }
Victor Stinner6345be92011-11-25 20:09:01 +01009226
Victor Stinner42bf7752011-11-21 22:52:58 +01009227 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009228 exc = NULL;
9229 raise_encode_exception(&exc, "decimal", unicode,
9230 startpos, startpos+1,
9231 "invalid decimal Unicode string");
9232 Py_XDECREF(exc);
9233 Py_DECREF(unicode);
9234 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009235 }
9236 /* 0-terminate the output string */
9237 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009238 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009239 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009240}
9241
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242/* --- Helpers ------------------------------------------------------------ */
9243
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009244/* helper macro to fixup start/end slice values */
9245#define ADJUST_INDICES(start, end, len) \
9246 if (end > len) \
9247 end = len; \
9248 else if (end < 0) { \
9249 end += len; \
9250 if (end < 0) \
9251 end = 0; \
9252 } \
9253 if (start < 0) { \
9254 start += len; \
9255 if (start < 0) \
9256 start = 0; \
9257 }
9258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009260any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009261 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009262 Py_ssize_t end,
9263 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009265 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009266 void *buf1, *buf2;
9267 Py_ssize_t len1, len2, result;
9268
9269 kind1 = PyUnicode_KIND(s1);
9270 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009271 if (kind1 < kind2)
9272 return -1;
9273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274 len1 = PyUnicode_GET_LENGTH(s1);
9275 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009276 ADJUST_INDICES(start, end, len1);
9277 if (end - start < len2)
9278 return -1;
9279
9280 buf1 = PyUnicode_DATA(s1);
9281 buf2 = PyUnicode_DATA(s2);
9282 if (len2 == 1) {
9283 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9284 result = findchar((const char *)buf1 + kind1*start,
9285 kind1, end - start, ch, direction);
9286 if (result == -1)
9287 return -1;
9288 else
9289 return start + result;
9290 }
9291
9292 if (kind2 != kind1) {
9293 buf2 = _PyUnicode_AsKind(s2, kind1);
9294 if (!buf2)
9295 return -2;
9296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297
Victor Stinner794d5672011-10-10 03:21:36 +02009298 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009299 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009300 case PyUnicode_1BYTE_KIND:
9301 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9302 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9303 else
9304 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9305 break;
9306 case PyUnicode_2BYTE_KIND:
9307 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9308 break;
9309 case PyUnicode_4BYTE_KIND:
9310 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9311 break;
9312 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009313 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009314 }
9315 }
9316 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009317 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009318 case PyUnicode_1BYTE_KIND:
9319 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9320 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9321 else
9322 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9323 break;
9324 case PyUnicode_2BYTE_KIND:
9325 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9326 break;
9327 case PyUnicode_4BYTE_KIND:
9328 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9329 break;
9330 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009331 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009332 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 }
9334
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009335 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 PyMem_Free(buf2);
9337
9338 return result;
9339}
9340
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009341/* _PyUnicode_InsertThousandsGrouping() helper functions */
9342#include "stringlib/localeutil.h"
9343
9344/**
9345 * InsertThousandsGrouping:
9346 * @writer: Unicode writer.
9347 * @n_buffer: Number of characters in @buffer.
9348 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9349 * @d_pos: Start of digits string.
9350 * @n_digits: The number of digits in the string, in which we want
9351 * to put the grouping chars.
9352 * @min_width: The minimum width of the digits in the output string.
9353 * Output will be zero-padded on the left to fill.
9354 * @grouping: see definition in localeconv().
9355 * @thousands_sep: see definition in localeconv().
9356 *
9357 * There are 2 modes: counting and filling. If @writer is NULL,
9358 * we are in counting mode, else filling mode.
9359 * If counting, the required buffer size is returned.
9360 * If filling, we know the buffer will be large enough, so we don't
9361 * need to pass in the buffer size.
9362 * Inserts thousand grouping characters (as defined by grouping and
9363 * thousands_sep) into @writer.
9364 *
9365 * Return value: -1 on error, number of characters otherwise.
9366 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009368_PyUnicode_InsertThousandsGrouping(
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009369 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009370 Py_ssize_t n_buffer,
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009371 PyObject *digits,
9372 Py_ssize_t d_pos,
9373 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009374 Py_ssize_t min_width,
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009375 const char *grouping,
9376 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009377 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009378{
Miss Islington (bot)9a413fa2019-01-07 07:26:20 -08009379 min_width = Py_MAX(0, min_width);
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009380 if (writer) {
9381 assert(digits != NULL);
9382 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009383 }
9384 else {
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009385 assert(digits == NULL);
9386 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009387 }
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009388 assert(0 <= d_pos);
9389 assert(0 <= n_digits);
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009390 assert(grouping != NULL);
9391
9392 if (digits != NULL) {
9393 if (PyUnicode_READY(digits) == -1) {
9394 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009395 }
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009396 }
9397 if (PyUnicode_READY(thousands_sep) == -1) {
9398 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009399 }
9400
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009401 Py_ssize_t count = 0;
9402 Py_ssize_t n_zeros;
9403 int loop_broken = 0;
9404 int use_separator = 0; /* First time through, don't append the
9405 separator. They only go between
9406 groups. */
9407 Py_ssize_t buffer_pos;
9408 Py_ssize_t digits_pos;
9409 Py_ssize_t len;
9410 Py_ssize_t n_chars;
9411 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9412 be looked at */
9413 /* A generator that returns all of the grouping widths, until it
9414 returns 0. */
9415 GroupGenerator groupgen;
9416 GroupGenerator_init(&groupgen, grouping);
9417 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9418
9419 /* if digits are not grouped, thousands separator
9420 should be an empty string */
9421 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9422
9423 digits_pos = d_pos + n_digits;
9424 if (writer) {
9425 buffer_pos = writer->pos + n_buffer;
9426 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9427 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 }
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009429 else {
9430 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009431 }
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009432
9433 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009434 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009435 }
Victor Stinner6f5fa1b2018-11-26 14:17:01 +01009436
9437 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9438 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9439 n_zeros = Py_MAX(0, len - remaining);
9440 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9441
9442 /* Use n_zero zero's and n_chars chars */
9443
9444 /* Count only, don't do anything. */
9445 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9446
9447 /* Copy into the writer. */
9448 InsertThousandsGrouping_fill(writer, &buffer_pos,
9449 digits, &digits_pos,
9450 n_chars, n_zeros,
9451 use_separator ? thousands_sep : NULL,
9452 thousands_sep_len, maxchar);
9453
9454 /* Use a separator next time. */
9455 use_separator = 1;
9456
9457 remaining -= n_chars;
9458 min_width -= len;
9459
9460 if (remaining <= 0 && min_width <= 0) {
9461 loop_broken = 1;
9462 break;
9463 }
9464 min_width -= thousands_sep_len;
9465 }
9466 if (!loop_broken) {
9467 /* We left the loop without using a break statement. */
9468
9469 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9470 n_zeros = Py_MAX(0, len - remaining);
9471 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9472
9473 /* Use n_zero zero's and n_chars chars */
9474 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9475
9476 /* Copy into the writer. */
9477 InsertThousandsGrouping_fill(writer, &buffer_pos,
9478 digits, &digits_pos,
9479 n_chars, n_zeros,
9480 use_separator ? thousands_sep : NULL,
9481 thousands_sep_len, maxchar);
9482 }
9483 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484}
9485
9486
Alexander Belopolsky40018472011-02-26 01:02:56 +00009487Py_ssize_t
9488PyUnicode_Count(PyObject *str,
9489 PyObject *substr,
9490 Py_ssize_t start,
9491 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009493 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009494 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 void *buf1 = NULL, *buf2 = NULL;
9496 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009497
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009498 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009499 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009500
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009501 kind1 = PyUnicode_KIND(str);
9502 kind2 = PyUnicode_KIND(substr);
9503 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009504 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009505
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009506 len1 = PyUnicode_GET_LENGTH(str);
9507 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009509 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009510 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009511
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009512 buf1 = PyUnicode_DATA(str);
9513 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009514 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009515 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009516 if (!buf2)
9517 goto onError;
9518 }
9519
9520 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009521 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009522 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009523 result = asciilib_count(
9524 ((Py_UCS1*)buf1) + start, end - start,
9525 buf2, len2, PY_SSIZE_T_MAX
9526 );
9527 else
9528 result = ucs1lib_count(
9529 ((Py_UCS1*)buf1) + start, end - start,
9530 buf2, len2, PY_SSIZE_T_MAX
9531 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532 break;
9533 case PyUnicode_2BYTE_KIND:
9534 result = ucs2lib_count(
9535 ((Py_UCS2*)buf1) + start, end - start,
9536 buf2, len2, PY_SSIZE_T_MAX
9537 );
9538 break;
9539 case PyUnicode_4BYTE_KIND:
9540 result = ucs4lib_count(
9541 ((Py_UCS4*)buf1) + start, end - start,
9542 buf2, len2, PY_SSIZE_T_MAX
9543 );
9544 break;
9545 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009546 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009548
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009549 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 PyMem_Free(buf2);
9551
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009554 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 PyMem_Free(buf2);
9556 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557}
9558
Alexander Belopolsky40018472011-02-26 01:02:56 +00009559Py_ssize_t
9560PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009561 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009562 Py_ssize_t start,
9563 Py_ssize_t end,
9564 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009565{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009566 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009568
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009569 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570}
9571
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572Py_ssize_t
9573PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9574 Py_ssize_t start, Py_ssize_t end,
9575 int direction)
9576{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009578 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 if (PyUnicode_READY(str) == -1)
9580 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009581 len = PyUnicode_GET_LENGTH(str);
9582 ADJUST_INDICES(start, end, len);
9583 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009584 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009586 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9587 kind, end-start, ch, direction);
9588 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009590 else
9591 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592}
9593
Alexander Belopolsky40018472011-02-26 01:02:56 +00009594static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009595tailmatch(PyObject *self,
9596 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009597 Py_ssize_t start,
9598 Py_ssize_t end,
9599 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009600{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009601 int kind_self;
9602 int kind_sub;
9603 void *data_self;
9604 void *data_sub;
9605 Py_ssize_t offset;
9606 Py_ssize_t i;
9607 Py_ssize_t end_sub;
9608
9609 if (PyUnicode_READY(self) == -1 ||
9610 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009611 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9614 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009616 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009618 if (PyUnicode_GET_LENGTH(substring) == 0)
9619 return 1;
9620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 kind_self = PyUnicode_KIND(self);
9622 data_self = PyUnicode_DATA(self);
9623 kind_sub = PyUnicode_KIND(substring);
9624 data_sub = PyUnicode_DATA(substring);
9625 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9626
9627 if (direction > 0)
9628 offset = end;
9629 else
9630 offset = start;
9631
9632 if (PyUnicode_READ(kind_self, data_self, offset) ==
9633 PyUnicode_READ(kind_sub, data_sub, 0) &&
9634 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9635 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9636 /* If both are of the same kind, memcmp is sufficient */
9637 if (kind_self == kind_sub) {
9638 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009639 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 data_sub,
9641 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009642 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009643 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009644 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009645 else {
9646 /* We do not need to compare 0 and len(substring)-1 because
9647 the if statement above ensured already that they are equal
9648 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 for (i = 1; i < end_sub; ++i) {
9650 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9651 PyUnicode_READ(kind_sub, data_sub, i))
9652 return 0;
9653 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009654 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009655 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656 }
9657
9658 return 0;
9659}
9660
Alexander Belopolsky40018472011-02-26 01:02:56 +00009661Py_ssize_t
9662PyUnicode_Tailmatch(PyObject *str,
9663 PyObject *substr,
9664 Py_ssize_t start,
9665 Py_ssize_t end,
9666 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009667{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009668 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009669 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009670
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009671 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672}
9673
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674static PyObject *
9675ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9678 char *resdata, *data = PyUnicode_DATA(self);
9679 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009680
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 res = PyUnicode_New(len, 127);
9682 if (res == NULL)
9683 return NULL;
9684 resdata = PyUnicode_DATA(res);
9685 if (lower)
9686 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009688 _Py_bytes_upper(resdata, data, len);
9689 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690}
9691
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695 Py_ssize_t j;
9696 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009697 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009698 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009699
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009700 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9701
9702 where ! is a negation and \p{xxx} is a character with property xxx.
9703 */
9704 for (j = i - 1; j >= 0; j--) {
9705 c = PyUnicode_READ(kind, data, j);
9706 if (!_PyUnicode_IsCaseIgnorable(c))
9707 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009708 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009709 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9710 if (final_sigma) {
9711 for (j = i + 1; j < length; j++) {
9712 c = PyUnicode_READ(kind, data, j);
9713 if (!_PyUnicode_IsCaseIgnorable(c))
9714 break;
9715 }
9716 final_sigma = j == length || !_PyUnicode_IsCased(c);
9717 }
9718 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009719}
9720
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009721static int
9722lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9723 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009724{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009725 /* Obscure special case. */
9726 if (c == 0x3A3) {
9727 mapped[0] = handle_capital_sigma(kind, data, length, i);
9728 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009730 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009731}
9732
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009733static Py_ssize_t
9734do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009735{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009736 Py_ssize_t i, k = 0;
9737 int n_res, j;
9738 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009739
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009740 c = PyUnicode_READ(kind, data, 0);
9741 n_res = _PyUnicode_ToUpperFull(c, mapped);
9742 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009743 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009744 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009746 for (i = 1; i < length; i++) {
9747 c = PyUnicode_READ(kind, data, i);
9748 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9749 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009750 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009751 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009752 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009753 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009754 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755}
9756
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009757static Py_ssize_t
9758do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9759 Py_ssize_t i, k = 0;
9760
9761 for (i = 0; i < length; i++) {
9762 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9763 int n_res, j;
9764 if (Py_UNICODE_ISUPPER(c)) {
9765 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9766 }
9767 else if (Py_UNICODE_ISLOWER(c)) {
9768 n_res = _PyUnicode_ToUpperFull(c, mapped);
9769 }
9770 else {
9771 n_res = 1;
9772 mapped[0] = c;
9773 }
9774 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009775 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009776 res[k++] = mapped[j];
9777 }
9778 }
9779 return k;
9780}
9781
9782static Py_ssize_t
9783do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9784 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009785{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009786 Py_ssize_t i, k = 0;
9787
9788 for (i = 0; i < length; i++) {
9789 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9790 int n_res, j;
9791 if (lower)
9792 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9793 else
9794 n_res = _PyUnicode_ToUpperFull(c, mapped);
9795 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009796 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009797 res[k++] = mapped[j];
9798 }
9799 }
9800 return k;
9801}
9802
9803static Py_ssize_t
9804do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9805{
9806 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9807}
9808
9809static Py_ssize_t
9810do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9811{
9812 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9813}
9814
Benjamin Petersone51757f2012-01-12 21:10:29 -05009815static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009816do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9817{
9818 Py_ssize_t i, k = 0;
9819
9820 for (i = 0; i < length; i++) {
9821 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9822 Py_UCS4 mapped[3];
9823 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9824 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009825 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009826 res[k++] = mapped[j];
9827 }
9828 }
9829 return k;
9830}
9831
9832static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009833do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9834{
9835 Py_ssize_t i, k = 0;
9836 int previous_is_cased;
9837
9838 previous_is_cased = 0;
9839 for (i = 0; i < length; i++) {
9840 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9841 Py_UCS4 mapped[3];
9842 int n_res, j;
9843
9844 if (previous_is_cased)
9845 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9846 else
9847 n_res = _PyUnicode_ToTitleFull(c, mapped);
9848
9849 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009850 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009851 res[k++] = mapped[j];
9852 }
9853
9854 previous_is_cased = _PyUnicode_IsCased(c);
9855 }
9856 return k;
9857}
9858
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009859static PyObject *
9860case_operation(PyObject *self,
9861 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9862{
9863 PyObject *res = NULL;
9864 Py_ssize_t length, newlength = 0;
9865 int kind, outkind;
9866 void *data, *outdata;
9867 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9868
Benjamin Petersoneea48462012-01-16 14:28:50 -05009869 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009870
9871 kind = PyUnicode_KIND(self);
9872 data = PyUnicode_DATA(self);
9873 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009874 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009875 PyErr_SetString(PyExc_OverflowError, "string is too long");
9876 return NULL;
9877 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009878 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009879 if (tmp == NULL)
9880 return PyErr_NoMemory();
9881 newlength = perform(kind, data, length, tmp, &maxchar);
9882 res = PyUnicode_New(newlength, maxchar);
9883 if (res == NULL)
9884 goto leave;
9885 tmpend = tmp + newlength;
9886 outdata = PyUnicode_DATA(res);
9887 outkind = PyUnicode_KIND(res);
9888 switch (outkind) {
9889 case PyUnicode_1BYTE_KIND:
9890 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9891 break;
9892 case PyUnicode_2BYTE_KIND:
9893 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9894 break;
9895 case PyUnicode_4BYTE_KIND:
9896 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9897 break;
9898 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009899 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009900 }
9901 leave:
9902 PyMem_FREE(tmp);
9903 return res;
9904}
9905
Tim Peters8ce9f162004-08-27 01:49:32 +00009906PyObject *
9907PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009908{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009909 PyObject *res;
9910 PyObject *fseq;
9911 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009912 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009913
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009914 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009915 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009916 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009917 }
9918
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009919 /* NOTE: the following code can't call back into Python code,
9920 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009921 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009922
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009923 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009924 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009925 res = _PyUnicode_JoinArray(separator, items, seqlen);
9926 Py_DECREF(fseq);
9927 return res;
9928}
9929
9930PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009931_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009932{
9933 PyObject *res = NULL; /* the result */
9934 PyObject *sep = NULL;
9935 Py_ssize_t seplen;
9936 PyObject *item;
9937 Py_ssize_t sz, i, res_offset;
9938 Py_UCS4 maxchar;
9939 Py_UCS4 item_maxchar;
9940 int use_memcpy;
9941 unsigned char *res_data = NULL, *sep_data = NULL;
9942 PyObject *last_obj;
9943 unsigned int kind = 0;
9944
Tim Peters05eba1f2004-08-27 21:32:02 +00009945 /* If empty sequence, return u"". */
9946 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009947 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009948 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009949
Tim Peters05eba1f2004-08-27 21:32:02 +00009950 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009951 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009952 if (seqlen == 1) {
9953 if (PyUnicode_CheckExact(items[0])) {
9954 res = items[0];
9955 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009956 return res;
9957 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009958 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009959 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009960 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009961 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009962 /* Set up sep and seplen */
9963 if (separator == NULL) {
9964 /* fall back to a blank space separator */
9965 sep = PyUnicode_FromOrdinal(' ');
9966 if (!sep)
9967 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009968 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009969 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009970 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009971 else {
9972 if (!PyUnicode_Check(separator)) {
9973 PyErr_Format(PyExc_TypeError,
9974 "separator: expected str instance,"
9975 " %.80s found",
9976 Py_TYPE(separator)->tp_name);
9977 goto onError;
9978 }
9979 if (PyUnicode_READY(separator))
9980 goto onError;
9981 sep = separator;
9982 seplen = PyUnicode_GET_LENGTH(separator);
9983 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9984 /* inc refcount to keep this code path symmetric with the
9985 above case of a blank separator */
9986 Py_INCREF(sep);
9987 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009988 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009989 }
9990
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009991 /* There are at least two things to join, or else we have a subclass
9992 * of str in the sequence.
9993 * Do a pre-pass to figure out the total amount of space we'll
9994 * need (sz), and see whether all argument are strings.
9995 */
9996 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009997#ifdef Py_DEBUG
9998 use_memcpy = 0;
9999#else
10000 use_memcpy = 1;
10001#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010002 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010003 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010004 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010005 if (!PyUnicode_Check(item)) {
10006 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010007 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010008 " %.80s found",
10009 i, Py_TYPE(item)->tp_name);
10010 goto onError;
10011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 if (PyUnicode_READY(item) == -1)
10013 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010014 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010016 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010017 if (i != 0) {
10018 add_sz += seplen;
10019 }
10020 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010021 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010022 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010023 goto onError;
10024 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010025 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010026 if (use_memcpy && last_obj != NULL) {
10027 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10028 use_memcpy = 0;
10029 }
10030 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010031 }
Tim Petersced69f82003-09-16 20:30:58 +000010032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010034 if (res == NULL)
10035 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010036
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010037 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010038#ifdef Py_DEBUG
10039 use_memcpy = 0;
10040#else
10041 if (use_memcpy) {
10042 res_data = PyUnicode_1BYTE_DATA(res);
10043 kind = PyUnicode_KIND(res);
10044 if (seplen != 0)
10045 sep_data = PyUnicode_1BYTE_DATA(sep);
10046 }
10047#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010048 if (use_memcpy) {
10049 for (i = 0; i < seqlen; ++i) {
10050 Py_ssize_t itemlen;
10051 item = items[i];
10052
10053 /* Copy item, and maybe the separator. */
10054 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010055 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010056 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010057 kind * seplen);
10058 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010059 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010060
10061 itemlen = PyUnicode_GET_LENGTH(item);
10062 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010063 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010064 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010065 kind * itemlen);
10066 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010067 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010068 }
10069 assert(res_data == PyUnicode_1BYTE_DATA(res)
10070 + kind * PyUnicode_GET_LENGTH(res));
10071 }
10072 else {
10073 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10074 Py_ssize_t itemlen;
10075 item = items[i];
10076
10077 /* Copy item, and maybe the separator. */
10078 if (i && seplen != 0) {
10079 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10080 res_offset += seplen;
10081 }
10082
10083 itemlen = PyUnicode_GET_LENGTH(item);
10084 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010085 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010086 res_offset += itemlen;
10087 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010088 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010089 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010090 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010093 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095
Benjamin Peterson29060642009-01-31 22:14:21 +000010096 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010098 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010099 return NULL;
10100}
10101
Victor Stinnerd3f08822012-05-29 12:57:52 +020010102void
10103_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10104 Py_UCS4 fill_char)
10105{
10106 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner7f9fb0f2018-11-27 12:42:04 +010010107 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010108 assert(PyUnicode_IS_READY(unicode));
10109 assert(unicode_modifiable(unicode));
10110 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10111 assert(start >= 0);
10112 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10113 FILL(kind, data, fill_char, start, length);
10114}
10115
Victor Stinner3fe55312012-01-04 00:33:50 +010010116Py_ssize_t
10117PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10118 Py_UCS4 fill_char)
10119{
10120 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010121
10122 if (!PyUnicode_Check(unicode)) {
10123 PyErr_BadInternalCall();
10124 return -1;
10125 }
10126 if (PyUnicode_READY(unicode) == -1)
10127 return -1;
10128 if (unicode_check_modifiable(unicode))
10129 return -1;
10130
Victor Stinnerd3f08822012-05-29 12:57:52 +020010131 if (start < 0) {
10132 PyErr_SetString(PyExc_IndexError, "string index out of range");
10133 return -1;
10134 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010135 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10136 PyErr_SetString(PyExc_ValueError,
10137 "fill character is bigger than "
10138 "the string maximum character");
10139 return -1;
10140 }
10141
10142 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10143 length = Py_MIN(maxlen, length);
10144 if (length <= 0)
10145 return 0;
10146
Victor Stinnerd3f08822012-05-29 12:57:52 +020010147 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010148 return length;
10149}
10150
Victor Stinner9310abb2011-10-05 00:59:23 +020010151static PyObject *
10152pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010153 Py_ssize_t left,
10154 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 PyObject *u;
10158 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010159 int kind;
10160 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010161
10162 if (left < 0)
10163 left = 0;
10164 if (right < 0)
10165 right = 0;
10166
Victor Stinnerc4b49542011-12-11 22:44:26 +010010167 if (left == 0 && right == 0)
10168 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10171 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010172 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10173 return NULL;
10174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010176 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010178 if (!u)
10179 return NULL;
10180
10181 kind = PyUnicode_KIND(u);
10182 data = PyUnicode_DATA(u);
10183 if (left)
10184 FILL(kind, data, fill, 0, left);
10185 if (right)
10186 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010187 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010188 assert(_PyUnicode_CheckConsistency(u, 1));
10189 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010190}
10191
Alexander Belopolsky40018472011-02-26 01:02:56 +000010192PyObject *
10193PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010194{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010195 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010196
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010197 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010198 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199
Benjamin Petersonead6b532011-12-20 17:23:42 -060010200 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010202 if (PyUnicode_IS_ASCII(string))
10203 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010204 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010205 PyUnicode_GET_LENGTH(string), keepends);
10206 else
10207 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010208 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010209 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 break;
10211 case PyUnicode_2BYTE_KIND:
10212 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010213 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 PyUnicode_GET_LENGTH(string), keepends);
10215 break;
10216 case PyUnicode_4BYTE_KIND:
10217 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010218 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 PyUnicode_GET_LENGTH(string), keepends);
10220 break;
10221 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010222 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010224 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010225}
10226
Alexander Belopolsky40018472011-02-26 01:02:56 +000010227static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010228split(PyObject *self,
10229 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010230 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010231{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010232 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 void *buf1, *buf2;
10234 Py_ssize_t len1, len2;
10235 PyObject* out;
10236
Guido van Rossumd57fd912000-03-10 22:53:23 +000010237 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010238 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 if (PyUnicode_READY(self) == -1)
10241 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010244 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010246 if (PyUnicode_IS_ASCII(self))
10247 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010249 PyUnicode_GET_LENGTH(self), maxcount
10250 );
10251 else
10252 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010253 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010254 PyUnicode_GET_LENGTH(self), maxcount
10255 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 case PyUnicode_2BYTE_KIND:
10257 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010258 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 PyUnicode_GET_LENGTH(self), maxcount
10260 );
10261 case PyUnicode_4BYTE_KIND:
10262 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010263 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 PyUnicode_GET_LENGTH(self), maxcount
10265 );
10266 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010267 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 }
10269
10270 if (PyUnicode_READY(substring) == -1)
10271 return NULL;
10272
10273 kind1 = PyUnicode_KIND(self);
10274 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 len1 = PyUnicode_GET_LENGTH(self);
10276 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010277 if (kind1 < kind2 || len1 < len2) {
10278 out = PyList_New(1);
10279 if (out == NULL)
10280 return NULL;
10281 Py_INCREF(self);
10282 PyList_SET_ITEM(out, 0, self);
10283 return out;
10284 }
10285 buf1 = PyUnicode_DATA(self);
10286 buf2 = PyUnicode_DATA(substring);
10287 if (kind2 != kind1) {
10288 buf2 = _PyUnicode_AsKind(substring, kind1);
10289 if (!buf2)
10290 return NULL;
10291 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010293 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010295 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10296 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010297 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010298 else
10299 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010300 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 break;
10302 case PyUnicode_2BYTE_KIND:
10303 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010304 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 break;
10306 case PyUnicode_4BYTE_KIND:
10307 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010308 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 break;
10310 default:
10311 out = NULL;
10312 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010313 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 PyMem_Free(buf2);
10315 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316}
10317
Alexander Belopolsky40018472011-02-26 01:02:56 +000010318static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010319rsplit(PyObject *self,
10320 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010321 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010322{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010323 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 void *buf1, *buf2;
10325 Py_ssize_t len1, len2;
10326 PyObject* out;
10327
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010328 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010329 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 if (PyUnicode_READY(self) == -1)
10332 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010333
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010335 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010337 if (PyUnicode_IS_ASCII(self))
10338 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010339 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010340 PyUnicode_GET_LENGTH(self), maxcount
10341 );
10342 else
10343 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010344 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010345 PyUnicode_GET_LENGTH(self), maxcount
10346 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 case PyUnicode_2BYTE_KIND:
10348 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010349 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 PyUnicode_GET_LENGTH(self), maxcount
10351 );
10352 case PyUnicode_4BYTE_KIND:
10353 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010354 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010355 PyUnicode_GET_LENGTH(self), maxcount
10356 );
10357 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010358 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 }
10360
10361 if (PyUnicode_READY(substring) == -1)
10362 return NULL;
10363
10364 kind1 = PyUnicode_KIND(self);
10365 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 len1 = PyUnicode_GET_LENGTH(self);
10367 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010368 if (kind1 < kind2 || len1 < len2) {
10369 out = PyList_New(1);
10370 if (out == NULL)
10371 return NULL;
10372 Py_INCREF(self);
10373 PyList_SET_ITEM(out, 0, self);
10374 return out;
10375 }
10376 buf1 = PyUnicode_DATA(self);
10377 buf2 = PyUnicode_DATA(substring);
10378 if (kind2 != kind1) {
10379 buf2 = _PyUnicode_AsKind(substring, kind1);
10380 if (!buf2)
10381 return NULL;
10382 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010384 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010386 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10387 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010388 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010389 else
10390 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010391 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 break;
10393 case PyUnicode_2BYTE_KIND:
10394 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010395 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 break;
10397 case PyUnicode_4BYTE_KIND:
10398 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010399 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 break;
10401 default:
10402 out = NULL;
10403 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010404 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 PyMem_Free(buf2);
10406 return out;
10407}
10408
10409static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010410anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10411 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010413 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10416 return asciilib_find(buf1, len1, buf2, len2, offset);
10417 else
10418 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 case PyUnicode_2BYTE_KIND:
10420 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10421 case PyUnicode_4BYTE_KIND:
10422 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10423 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010424 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425}
10426
10427static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010428anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10429 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010431 switch (kind) {
10432 case PyUnicode_1BYTE_KIND:
10433 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10434 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10435 else
10436 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10437 case PyUnicode_2BYTE_KIND:
10438 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10439 case PyUnicode_4BYTE_KIND:
10440 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10441 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010442 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010443}
10444
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010445static void
10446replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10447 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10448{
10449 int kind = PyUnicode_KIND(u);
10450 void *data = PyUnicode_DATA(u);
10451 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10452 if (kind == PyUnicode_1BYTE_KIND) {
10453 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10454 (Py_UCS1 *)data + len,
10455 u1, u2, maxcount);
10456 }
10457 else if (kind == PyUnicode_2BYTE_KIND) {
10458 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10459 (Py_UCS2 *)data + len,
10460 u1, u2, maxcount);
10461 }
10462 else {
10463 assert(kind == PyUnicode_4BYTE_KIND);
10464 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10465 (Py_UCS4 *)data + len,
10466 u1, u2, maxcount);
10467 }
10468}
10469
Alexander Belopolsky40018472011-02-26 01:02:56 +000010470static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471replace(PyObject *self, PyObject *str1,
10472 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010473{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 PyObject *u;
10475 char *sbuf = PyUnicode_DATA(self);
10476 char *buf1 = PyUnicode_DATA(str1);
10477 char *buf2 = PyUnicode_DATA(str2);
10478 int srelease = 0, release1 = 0, release2 = 0;
10479 int skind = PyUnicode_KIND(self);
10480 int kind1 = PyUnicode_KIND(str1);
10481 int kind2 = PyUnicode_KIND(str2);
10482 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10483 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10484 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010485 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010486 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487
10488 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010489 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010491 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492
Victor Stinner59de0ee2011-10-07 10:01:28 +020010493 if (str1 == str2)
10494 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495
Victor Stinner49a0a212011-10-12 23:46:10 +020010496 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010497 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10498 if (maxchar < maxchar_str1)
10499 /* substring too wide to be present */
10500 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010501 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10502 /* Replacing str1 with str2 may cause a maxchar reduction in the
10503 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010504 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010505 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010507 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010508 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010510 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010512 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010513 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010514 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010515
Victor Stinner69ed0f42013-04-09 21:48:24 +020010516 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010517 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010518 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010520 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010522 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010524
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010525 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10526 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010527 }
10528 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 int rkind = skind;
10530 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010531 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 if (kind1 < rkind) {
10534 /* widen substring */
10535 buf1 = _PyUnicode_AsKind(str1, rkind);
10536 if (!buf1) goto error;
10537 release1 = 1;
10538 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010539 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010540 if (i < 0)
10541 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 if (rkind > kind2) {
10543 /* widen replacement */
10544 buf2 = _PyUnicode_AsKind(str2, rkind);
10545 if (!buf2) goto error;
10546 release2 = 1;
10547 }
10548 else if (rkind < kind2) {
10549 /* widen self and buf1 */
10550 rkind = kind2;
10551 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010552 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 sbuf = _PyUnicode_AsKind(self, rkind);
10554 if (!sbuf) goto error;
10555 srelease = 1;
10556 buf1 = _PyUnicode_AsKind(str1, rkind);
10557 if (!buf1) goto error;
10558 release1 = 1;
10559 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010560 u = PyUnicode_New(slen, maxchar);
10561 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010563 assert(PyUnicode_KIND(u) == rkind);
10564 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010565
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010566 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010567 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010568 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010570 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010572
10573 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010574 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010575 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010576 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010577 if (i == -1)
10578 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010579 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010581 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010583 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010585 }
10586 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010588 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 int rkind = skind;
10590 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010593 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 buf1 = _PyUnicode_AsKind(str1, rkind);
10595 if (!buf1) goto error;
10596 release1 = 1;
10597 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010598 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010599 if (n == 0)
10600 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010602 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 buf2 = _PyUnicode_AsKind(str2, rkind);
10604 if (!buf2) goto error;
10605 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010608 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 rkind = kind2;
10610 sbuf = _PyUnicode_AsKind(self, rkind);
10611 if (!sbuf) goto error;
10612 srelease = 1;
10613 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010614 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 buf1 = _PyUnicode_AsKind(str1, rkind);
10616 if (!buf1) goto error;
10617 release1 = 1;
10618 }
10619 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10620 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010621 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 PyErr_SetString(PyExc_OverflowError,
10623 "replace string is too long");
10624 goto error;
10625 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010626 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010627 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010628 _Py_INCREF_UNICODE_EMPTY();
10629 if (!unicode_empty)
10630 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010631 u = unicode_empty;
10632 goto done;
10633 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010634 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 PyErr_SetString(PyExc_OverflowError,
10636 "replace string is too long");
10637 goto error;
10638 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010639 u = PyUnicode_New(new_size, maxchar);
10640 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010642 assert(PyUnicode_KIND(u) == rkind);
10643 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 ires = i = 0;
10645 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010646 while (n-- > 0) {
10647 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010648 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010649 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010650 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010651 if (j == -1)
10652 break;
10653 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010654 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010655 memcpy(res + rkind * ires,
10656 sbuf + rkind * i,
10657 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010659 }
10660 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010662 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010664 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010666 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010671 memcpy(res + rkind * ires,
10672 sbuf + rkind * i,
10673 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010674 }
10675 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010676 /* interleave */
10677 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010678 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010680 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010682 if (--n <= 0)
10683 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010684 memcpy(res + rkind * ires,
10685 sbuf + rkind * i,
10686 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 ires++;
10688 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010689 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010690 memcpy(res + rkind * ires,
10691 sbuf + rkind * i,
10692 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010693 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010694 }
10695
10696 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010697 unicode_adjust_maxchar(&u);
10698 if (u == NULL)
10699 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010701
10702 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 if (srelease)
10704 PyMem_FREE(sbuf);
10705 if (release1)
10706 PyMem_FREE(buf1);
10707 if (release2)
10708 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010709 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010711
Benjamin Peterson29060642009-01-31 22:14:21 +000010712 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010713 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 if (srelease)
10715 PyMem_FREE(sbuf);
10716 if (release1)
10717 PyMem_FREE(buf1);
10718 if (release2)
10719 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010720 return unicode_result_unchanged(self);
10721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010722 error:
10723 if (srelease && sbuf)
10724 PyMem_FREE(sbuf);
10725 if (release1 && buf1)
10726 PyMem_FREE(buf1);
10727 if (release2 && buf2)
10728 PyMem_FREE(buf2);
10729 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730}
10731
10732/* --- Unicode Object Methods --------------------------------------------- */
10733
INADA Naoki3ae20562017-01-16 20:41:20 +090010734/*[clinic input]
10735str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010736
INADA Naoki3ae20562017-01-16 20:41:20 +090010737Return a version of the string where each word is titlecased.
10738
10739More specifically, words start with uppercased characters and all remaining
10740cased characters have lower case.
10741[clinic start generated code]*/
10742
10743static PyObject *
10744unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010745/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010747 if (PyUnicode_READY(self) == -1)
10748 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010749 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750}
10751
INADA Naoki3ae20562017-01-16 20:41:20 +090010752/*[clinic input]
10753str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754
INADA Naoki3ae20562017-01-16 20:41:20 +090010755Return a capitalized version of the string.
10756
10757More specifically, make the first character have upper case and the rest lower
10758case.
10759[clinic start generated code]*/
10760
10761static PyObject *
10762unicode_capitalize_impl(PyObject *self)
10763/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010765 if (PyUnicode_READY(self) == -1)
10766 return NULL;
10767 if (PyUnicode_GET_LENGTH(self) == 0)
10768 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010769 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770}
10771
INADA Naoki3ae20562017-01-16 20:41:20 +090010772/*[clinic input]
10773str.casefold as unicode_casefold
10774
10775Return a version of the string suitable for caseless comparisons.
10776[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010777
10778static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010779unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010780/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010781{
10782 if (PyUnicode_READY(self) == -1)
10783 return NULL;
10784 if (PyUnicode_IS_ASCII(self))
10785 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010786 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010787}
10788
10789
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010790/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010791
10792static int
10793convert_uc(PyObject *obj, void *addr)
10794{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010796
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010797 if (!PyUnicode_Check(obj)) {
10798 PyErr_Format(PyExc_TypeError,
10799 "The fill character must be a unicode character, "
10800 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010801 return 0;
10802 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010803 if (PyUnicode_READY(obj) < 0)
10804 return 0;
10805 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010806 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010807 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010808 return 0;
10809 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010810 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010811 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010812}
10813
INADA Naoki3ae20562017-01-16 20:41:20 +090010814/*[clinic input]
10815str.center as unicode_center
10816
10817 width: Py_ssize_t
10818 fillchar: Py_UCS4 = ' '
10819 /
10820
10821Return a centered string of length width.
10822
10823Padding is done using the specified fill character (default is a space).
10824[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825
10826static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010827unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10828/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010829{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010830 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010831
Benjamin Petersonbac79492012-01-14 13:34:47 -050010832 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833 return NULL;
10834
Victor Stinnerc4b49542011-12-11 22:44:26 +010010835 if (PyUnicode_GET_LENGTH(self) >= width)
10836 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010837
Victor Stinnerc4b49542011-12-11 22:44:26 +010010838 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839 left = marg / 2 + (marg & width & 1);
10840
Victor Stinner9310abb2011-10-05 00:59:23 +020010841 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842}
10843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844/* This function assumes that str1 and str2 are readied by the caller. */
10845
Marc-André Lemburge5034372000-08-08 08:04:29 +000010846static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010847unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010848{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010849#define COMPARE(TYPE1, TYPE2) \
10850 do { \
10851 TYPE1* p1 = (TYPE1 *)data1; \
10852 TYPE2* p2 = (TYPE2 *)data2; \
10853 TYPE1* end = p1 + len; \
10854 Py_UCS4 c1, c2; \
10855 for (; p1 != end; p1++, p2++) { \
10856 c1 = *p1; \
10857 c2 = *p2; \
10858 if (c1 != c2) \
10859 return (c1 < c2) ? -1 : 1; \
10860 } \
10861 } \
10862 while (0)
10863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010864 int kind1, kind2;
10865 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010866 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010867
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010868 kind1 = PyUnicode_KIND(str1);
10869 kind2 = PyUnicode_KIND(str2);
10870 data1 = PyUnicode_DATA(str1);
10871 data2 = PyUnicode_DATA(str2);
10872 len1 = PyUnicode_GET_LENGTH(str1);
10873 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010874 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010875
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010876 switch(kind1) {
10877 case PyUnicode_1BYTE_KIND:
10878 {
10879 switch(kind2) {
10880 case PyUnicode_1BYTE_KIND:
10881 {
10882 int cmp = memcmp(data1, data2, len);
10883 /* normalize result of memcmp() into the range [-1; 1] */
10884 if (cmp < 0)
10885 return -1;
10886 if (cmp > 0)
10887 return 1;
10888 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010889 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010890 case PyUnicode_2BYTE_KIND:
10891 COMPARE(Py_UCS1, Py_UCS2);
10892 break;
10893 case PyUnicode_4BYTE_KIND:
10894 COMPARE(Py_UCS1, Py_UCS4);
10895 break;
10896 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010897 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010898 }
10899 break;
10900 }
10901 case PyUnicode_2BYTE_KIND:
10902 {
10903 switch(kind2) {
10904 case PyUnicode_1BYTE_KIND:
10905 COMPARE(Py_UCS2, Py_UCS1);
10906 break;
10907 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010908 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010909 COMPARE(Py_UCS2, Py_UCS2);
10910 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010911 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010912 case PyUnicode_4BYTE_KIND:
10913 COMPARE(Py_UCS2, Py_UCS4);
10914 break;
10915 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010916 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010917 }
10918 break;
10919 }
10920 case PyUnicode_4BYTE_KIND:
10921 {
10922 switch(kind2) {
10923 case PyUnicode_1BYTE_KIND:
10924 COMPARE(Py_UCS4, Py_UCS1);
10925 break;
10926 case PyUnicode_2BYTE_KIND:
10927 COMPARE(Py_UCS4, Py_UCS2);
10928 break;
10929 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010930 {
10931#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10932 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10933 /* normalize result of wmemcmp() into the range [-1; 1] */
10934 if (cmp < 0)
10935 return -1;
10936 if (cmp > 0)
10937 return 1;
10938#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010939 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010940#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010941 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010942 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010943 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010944 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010945 }
10946 break;
10947 }
10948 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010949 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010950 }
10951
Victor Stinner770e19e2012-10-04 22:59:45 +020010952 if (len1 == len2)
10953 return 0;
10954 if (len1 < len2)
10955 return -1;
10956 else
10957 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010958
10959#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010960}
10961
Benjamin Peterson621b4302016-09-09 13:54:34 -070010962static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010963unicode_compare_eq(PyObject *str1, PyObject *str2)
10964{
10965 int kind;
10966 void *data1, *data2;
10967 Py_ssize_t len;
10968 int cmp;
10969
Victor Stinnere5567ad2012-10-23 02:48:49 +020010970 len = PyUnicode_GET_LENGTH(str1);
10971 if (PyUnicode_GET_LENGTH(str2) != len)
10972 return 0;
10973 kind = PyUnicode_KIND(str1);
10974 if (PyUnicode_KIND(str2) != kind)
10975 return 0;
10976 data1 = PyUnicode_DATA(str1);
10977 data2 = PyUnicode_DATA(str2);
10978
10979 cmp = memcmp(data1, data2, len * kind);
10980 return (cmp == 0);
10981}
10982
10983
Alexander Belopolsky40018472011-02-26 01:02:56 +000010984int
10985PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10988 if (PyUnicode_READY(left) == -1 ||
10989 PyUnicode_READY(right) == -1)
10990 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010991
10992 /* a string is equal to itself */
10993 if (left == right)
10994 return 0;
10995
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010996 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010998 PyErr_Format(PyExc_TypeError,
10999 "Can't compare %.100s and %.100s",
11000 left->ob_type->tp_name,
11001 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 return -1;
11003}
11004
Martin v. Löwis5b222132007-06-10 09:51:05 +000011005int
11006PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011008 Py_ssize_t i;
11009 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011011 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011012
Victor Stinner910337b2011-10-03 03:20:16 +020011013 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011014 if (!PyUnicode_IS_READY(uni)) {
11015 const wchar_t *ws = _PyUnicode_WSTR(uni);
11016 /* Compare Unicode string and source character set string */
11017 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11018 if (chr != ustr[i])
11019 return (chr < ustr[i]) ? -1 : 1;
11020 }
11021 /* This check keeps Python strings that end in '\0' from comparing equal
11022 to C strings identical up to that point. */
11023 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11024 return 1; /* uni is longer */
11025 if (ustr[i])
11026 return -1; /* str is longer */
11027 return 0;
11028 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011029 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011030 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011031 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011032 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011033 size_t len, len2 = strlen(str);
11034 int cmp;
11035
11036 len = Py_MIN(len1, len2);
11037 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011038 if (cmp != 0) {
11039 if (cmp < 0)
11040 return -1;
11041 else
11042 return 1;
11043 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011044 if (len1 > len2)
11045 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011046 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011047 return -1; /* str is longer */
11048 return 0;
11049 }
11050 else {
11051 void *data = PyUnicode_DATA(uni);
11052 /* Compare Unicode string and source character set string */
11053 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011054 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011055 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11056 /* This check keeps Python strings that end in '\0' from comparing equal
11057 to C strings identical up to that point. */
11058 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11059 return 1; /* uni is longer */
11060 if (str[i])
11061 return -1; /* str is longer */
11062 return 0;
11063 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011064}
11065
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011066static int
11067non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11068{
11069 size_t i, len;
11070 const wchar_t *p;
11071 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11072 if (strlen(str) != len)
11073 return 0;
11074 p = _PyUnicode_WSTR(unicode);
11075 assert(p);
11076 for (i = 0; i < len; i++) {
11077 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011078 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011079 return 0;
11080 }
11081 return 1;
11082}
11083
11084int
11085_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11086{
11087 size_t len;
11088 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011089 assert(str);
11090#ifndef NDEBUG
11091 for (const char *p = str; *p; p++) {
11092 assert((unsigned char)*p < 128);
11093 }
11094#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011095 if (PyUnicode_READY(unicode) == -1) {
11096 /* Memory error or bad data */
11097 PyErr_Clear();
11098 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11099 }
11100 if (!PyUnicode_IS_ASCII(unicode))
11101 return 0;
11102 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11103 return strlen(str) == len &&
11104 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11105}
11106
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011107int
11108_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11109{
11110 PyObject *right_uni;
11111 Py_hash_t hash;
11112
11113 assert(_PyUnicode_CHECK(left));
11114 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011115#ifndef NDEBUG
11116 for (const char *p = right->string; *p; p++) {
11117 assert((unsigned char)*p < 128);
11118 }
11119#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011120
11121 if (PyUnicode_READY(left) == -1) {
11122 /* memory error or bad data */
11123 PyErr_Clear();
11124 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11125 }
11126
11127 if (!PyUnicode_IS_ASCII(left))
11128 return 0;
11129
11130 right_uni = _PyUnicode_FromId(right); /* borrowed */
11131 if (right_uni == NULL) {
11132 /* memory error or bad data */
11133 PyErr_Clear();
11134 return _PyUnicode_EqualToASCIIString(left, right->string);
11135 }
11136
11137 if (left == right_uni)
11138 return 1;
11139
11140 if (PyUnicode_CHECK_INTERNED(left))
11141 return 0;
11142
INADA Naoki7cc95f52018-01-28 02:07:09 +090011143 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011144 hash = _PyUnicode_HASH(left);
11145 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11146 return 0;
11147
11148 return unicode_compare_eq(left, right_uni);
11149}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011150
Alexander Belopolsky40018472011-02-26 01:02:56 +000011151PyObject *
11152PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011153{
11154 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011155
Victor Stinnere5567ad2012-10-23 02:48:49 +020011156 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11157 Py_RETURN_NOTIMPLEMENTED;
11158
11159 if (PyUnicode_READY(left) == -1 ||
11160 PyUnicode_READY(right) == -1)
11161 return NULL;
11162
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011163 if (left == right) {
11164 switch (op) {
11165 case Py_EQ:
11166 case Py_LE:
11167 case Py_GE:
11168 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011169 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011170 case Py_NE:
11171 case Py_LT:
11172 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011173 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011174 default:
11175 PyErr_BadArgument();
11176 return NULL;
11177 }
11178 }
11179 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011180 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011181 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011182 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011183 }
11184 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011185 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011186 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011187 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011188}
11189
Alexander Belopolsky40018472011-02-26 01:02:56 +000011190int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011191_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11192{
11193 return unicode_eq(aa, bb);
11194}
11195
11196int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011197PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011198{
Victor Stinner77282cb2013-04-14 19:22:47 +020011199 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011200 void *buf1, *buf2;
11201 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011202 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011203
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011204 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011205 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011206 "'in <string>' requires string as left operand, not %.100s",
11207 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011208 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011209 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011210 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011211 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011212 if (ensure_unicode(str) < 0)
11213 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011215 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011216 kind2 = PyUnicode_KIND(substr);
11217 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011218 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011219 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011220 len2 = PyUnicode_GET_LENGTH(substr);
11221 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011222 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011223 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011224 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011225 if (len2 == 1) {
11226 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11227 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011228 return result;
11229 }
11230 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011231 buf2 = _PyUnicode_AsKind(substr, kind1);
11232 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011233 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011234 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011235
Victor Stinner77282cb2013-04-14 19:22:47 +020011236 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 case PyUnicode_1BYTE_KIND:
11238 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11239 break;
11240 case PyUnicode_2BYTE_KIND:
11241 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11242 break;
11243 case PyUnicode_4BYTE_KIND:
11244 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11245 break;
11246 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011247 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011249
Victor Stinner77282cb2013-04-14 19:22:47 +020011250 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 PyMem_Free(buf2);
11252
Guido van Rossum403d68b2000-03-13 15:55:09 +000011253 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011254}
11255
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256/* Concat to string or Unicode object giving a new Unicode object. */
11257
Alexander Belopolsky40018472011-02-26 01:02:56 +000011258PyObject *
11259PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011261 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011262 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011263 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011265 if (ensure_unicode(left) < 0)
11266 return NULL;
11267
11268 if (!PyUnicode_Check(right)) {
11269 PyErr_Format(PyExc_TypeError,
11270 "can only concatenate str (not \"%.200s\") to str",
11271 right->ob_type->tp_name);
11272 return NULL;
11273 }
11274 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011275 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276
11277 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011278 if (left == unicode_empty)
11279 return PyUnicode_FromObject(right);
11280 if (right == unicode_empty)
11281 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011283 left_len = PyUnicode_GET_LENGTH(left);
11284 right_len = PyUnicode_GET_LENGTH(right);
11285 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011286 PyErr_SetString(PyExc_OverflowError,
11287 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011288 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011289 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011290 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011291
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011292 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11293 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011294 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011297 result = PyUnicode_New(new_len, maxchar);
11298 if (result == NULL)
11299 return NULL;
11300 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11301 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11302 assert(_PyUnicode_CheckConsistency(result, 1));
11303 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304}
11305
Walter Dörwald1ab83302007-05-18 17:15:44 +000011306void
Victor Stinner23e56682011-10-03 03:54:37 +020011307PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011308{
Victor Stinner23e56682011-10-03 03:54:37 +020011309 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011310 Py_UCS4 maxchar, maxchar2;
11311 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011312
11313 if (p_left == NULL) {
11314 if (!PyErr_Occurred())
11315 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011316 return;
11317 }
Victor Stinner23e56682011-10-03 03:54:37 +020011318 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011319 if (right == NULL || left == NULL
11320 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011321 if (!PyErr_Occurred())
11322 PyErr_BadInternalCall();
11323 goto error;
11324 }
11325
Benjamin Petersonbac79492012-01-14 13:34:47 -050011326 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011327 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011328 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011329 goto error;
11330
Victor Stinner488fa492011-12-12 00:01:39 +010011331 /* Shortcuts */
11332 if (left == unicode_empty) {
11333 Py_DECREF(left);
11334 Py_INCREF(right);
11335 *p_left = right;
11336 return;
11337 }
11338 if (right == unicode_empty)
11339 return;
11340
11341 left_len = PyUnicode_GET_LENGTH(left);
11342 right_len = PyUnicode_GET_LENGTH(right);
11343 if (left_len > PY_SSIZE_T_MAX - right_len) {
11344 PyErr_SetString(PyExc_OverflowError,
11345 "strings are too large to concat");
11346 goto error;
11347 }
11348 new_len = left_len + right_len;
11349
11350 if (unicode_modifiable(left)
11351 && PyUnicode_CheckExact(right)
11352 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011353 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11354 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011355 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011356 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011357 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11358 {
11359 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011360 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011361 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011362
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011363 /* copy 'right' into the newly allocated area of 'left' */
11364 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011365 }
Victor Stinner488fa492011-12-12 00:01:39 +010011366 else {
11367 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11368 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011369 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011370
Victor Stinner488fa492011-12-12 00:01:39 +010011371 /* Concat the two Unicode strings */
11372 res = PyUnicode_New(new_len, maxchar);
11373 if (res == NULL)
11374 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011375 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11376 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011377 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011378 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011379 }
11380 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011381 return;
11382
11383error:
Victor Stinner488fa492011-12-12 00:01:39 +010011384 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011385}
11386
11387void
11388PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11389{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011390 PyUnicode_Append(pleft, right);
11391 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011392}
11393
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011394/*
11395Wraps stringlib_parse_args_finds() and additionally ensures that the
11396first argument is a unicode object.
11397*/
11398
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011399static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011400parse_args_finds_unicode(const char * function_name, PyObject *args,
11401 PyObject **substring,
11402 Py_ssize_t *start, Py_ssize_t *end)
11403{
11404 if(stringlib_parse_args_finds(function_name, args, substring,
11405 start, end)) {
11406 if (ensure_unicode(*substring) < 0)
11407 return 0;
11408 return 1;
11409 }
11410 return 0;
11411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011416Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011417string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011418interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
11420static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011421unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011423 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011424 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011425 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011427 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 void *buf1, *buf2;
11429 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011431 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 kind1 = PyUnicode_KIND(self);
11435 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011436 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011437 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 len1 = PyUnicode_GET_LENGTH(self);
11440 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011442 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011443 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011444
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011445 buf1 = PyUnicode_DATA(self);
11446 buf2 = PyUnicode_DATA(substring);
11447 if (kind2 != kind1) {
11448 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011449 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011450 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011451 }
11452 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 case PyUnicode_1BYTE_KIND:
11454 iresult = ucs1lib_count(
11455 ((Py_UCS1*)buf1) + start, end - start,
11456 buf2, len2, PY_SSIZE_T_MAX
11457 );
11458 break;
11459 case PyUnicode_2BYTE_KIND:
11460 iresult = ucs2lib_count(
11461 ((Py_UCS2*)buf1) + start, end - start,
11462 buf2, len2, PY_SSIZE_T_MAX
11463 );
11464 break;
11465 case PyUnicode_4BYTE_KIND:
11466 iresult = ucs4lib_count(
11467 ((Py_UCS4*)buf1) + start, end - start,
11468 buf2, len2, PY_SSIZE_T_MAX
11469 );
11470 break;
11471 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011472 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 }
11474
11475 result = PyLong_FromSsize_t(iresult);
11476
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011477 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 return result;
11481}
11482
INADA Naoki3ae20562017-01-16 20:41:20 +090011483/*[clinic input]
11484str.encode as unicode_encode
11485
11486 encoding: str(c_default="NULL") = 'utf-8'
11487 The encoding in which to encode the string.
11488 errors: str(c_default="NULL") = 'strict'
11489 The error handling scheme to use for encoding errors.
11490 The default is 'strict' meaning that encoding errors raise a
11491 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11492 'xmlcharrefreplace' as well as any other name registered with
11493 codecs.register_error that can handle UnicodeEncodeErrors.
11494
11495Encode the string using the codec registered for encoding.
11496[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
11498static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011499unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011500/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011502 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011503}
11504
INADA Naoki3ae20562017-01-16 20:41:20 +090011505/*[clinic input]
11506str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507
INADA Naoki3ae20562017-01-16 20:41:20 +090011508 tabsize: int = 8
11509
11510Return a copy where all tab characters are expanded using spaces.
11511
11512If tabsize is not given, a tab size of 8 characters is assumed.
11513[clinic start generated code]*/
11514
11515static PyObject *
11516unicode_expandtabs_impl(PyObject *self, int tabsize)
11517/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011519 Py_ssize_t i, j, line_pos, src_len, incr;
11520 Py_UCS4 ch;
11521 PyObject *u;
11522 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011523 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011524 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525
Antoine Pitrou22425222011-10-04 19:10:51 +020011526 if (PyUnicode_READY(self) == -1)
11527 return NULL;
11528
Thomas Wouters7e474022000-07-16 12:04:32 +000011529 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011530 src_len = PyUnicode_GET_LENGTH(self);
11531 i = j = line_pos = 0;
11532 kind = PyUnicode_KIND(self);
11533 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011534 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011535 for (; i < src_len; i++) {
11536 ch = PyUnicode_READ(kind, src_data, i);
11537 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011538 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011540 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011541 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011542 goto overflow;
11543 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011544 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011545 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011546 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011549 goto overflow;
11550 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011552 if (ch == '\n' || ch == '\r')
11553 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011555 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011556 if (!found)
11557 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011558
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011560 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561 if (!u)
11562 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011563 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
Antoine Pitroue71d5742011-10-04 15:55:09 +020011565 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566
Antoine Pitroue71d5742011-10-04 15:55:09 +020011567 for (; i < src_len; i++) {
11568 ch = PyUnicode_READ(kind, src_data, i);
11569 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011571 incr = tabsize - (line_pos % tabsize);
11572 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011573 FILL(kind, dest_data, ' ', j, incr);
11574 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011575 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011576 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011578 line_pos++;
11579 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011580 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011581 if (ch == '\n' || ch == '\r')
11582 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011584 }
11585 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011586 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011587
Antoine Pitroue71d5742011-10-04 15:55:09 +020011588 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011589 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11590 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
11596Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011597such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598arguments start and end are interpreted as in slice notation.\n\
11599\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011600Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
11602static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011605 /* initialize variables to prevent gcc warning */
11606 PyObject *substring = NULL;
11607 Py_ssize_t start = 0;
11608 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011609 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011611 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011614 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011617 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (result == -2)
11620 return NULL;
11621
Christian Heimes217cfd12007-12-02 14:31:20 +000011622 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623}
11624
11625static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011626unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011628 void *data;
11629 enum PyUnicode_Kind kind;
11630 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011631
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011632 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011633 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011635 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011636 if (PyUnicode_READY(self) == -1) {
11637 return NULL;
11638 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011639 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11640 PyErr_SetString(PyExc_IndexError, "string index out of range");
11641 return NULL;
11642 }
11643 kind = PyUnicode_KIND(self);
11644 data = PyUnicode_DATA(self);
11645 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011646 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647}
11648
Guido van Rossumc2504932007-09-18 19:42:40 +000011649/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011650 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011651static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011652unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011653{
Guido van Rossumc2504932007-09-18 19:42:40 +000011654 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011655 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011656
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011657#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011658 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011659#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 if (_PyUnicode_HASH(self) != -1)
11661 return _PyUnicode_HASH(self);
11662 if (PyUnicode_READY(self) == -1)
11663 return -1;
11664 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011665 /*
11666 We make the hash of the empty string be 0, rather than using
11667 (prefix ^ suffix), since this slightly obfuscates the hash secret
11668 */
11669 if (len == 0) {
11670 _PyUnicode_HASH(self) = 0;
11671 return 0;
11672 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011673 x = _Py_HashBytes(PyUnicode_DATA(self),
11674 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011676 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677}
11678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011679PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011680 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011682Return the lowest index in S where substring sub is found, \n\
11683such that sub is contained within S[start:end]. Optional\n\
11684arguments start and end are interpreted as in slice notation.\n\
11685\n\
11686Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
11688static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011691 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011692 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011693 PyObject *substring = NULL;
11694 Py_ssize_t start = 0;
11695 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011697 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011700 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011702
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011703 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 if (result == -2)
11706 return NULL;
11707
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708 if (result < 0) {
11709 PyErr_SetString(PyExc_ValueError, "substring not found");
11710 return NULL;
11711 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011712
Christian Heimes217cfd12007-12-02 14:31:20 +000011713 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714}
11715
INADA Naoki3ae20562017-01-16 20:41:20 +090011716/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011717str.isascii as unicode_isascii
11718
11719Return True if all characters in the string are ASCII, False otherwise.
11720
11721ASCII characters have code points in the range U+0000-U+007F.
11722Empty string is ASCII too.
11723[clinic start generated code]*/
11724
11725static PyObject *
11726unicode_isascii_impl(PyObject *self)
11727/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11728{
11729 if (PyUnicode_READY(self) == -1) {
11730 return NULL;
11731 }
11732 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11733}
11734
11735/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011736str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737
INADA Naoki3ae20562017-01-16 20:41:20 +090011738Return True if the string is a lowercase string, False otherwise.
11739
11740A string is lowercase if all cased characters in the string are lowercase and
11741there is at least one cased character in the string.
11742[clinic start generated code]*/
11743
11744static PyObject *
11745unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011746/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 Py_ssize_t i, length;
11749 int kind;
11750 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751 int cased;
11752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 if (PyUnicode_READY(self) == -1)
11754 return NULL;
11755 length = PyUnicode_GET_LENGTH(self);
11756 kind = PyUnicode_KIND(self);
11757 data = PyUnicode_DATA(self);
11758
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 if (length == 1)
11761 return PyBool_FromLong(
11762 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011764 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011766 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011767
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 for (i = 0; i < length; i++) {
11770 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011771
Benjamin Peterson29060642009-01-31 22:14:21 +000011772 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011773 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011774 else if (!cased && Py_UNICODE_ISLOWER(ch))
11775 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011777 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778}
11779
INADA Naoki3ae20562017-01-16 20:41:20 +090011780/*[clinic input]
11781str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782
INADA Naoki3ae20562017-01-16 20:41:20 +090011783Return True if the string is an uppercase string, False otherwise.
11784
11785A string is uppercase if all cased characters in the string are uppercase and
11786there is at least one cased character in the string.
11787[clinic start generated code]*/
11788
11789static PyObject *
11790unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011791/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 Py_ssize_t i, length;
11794 int kind;
11795 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796 int cased;
11797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 if (PyUnicode_READY(self) == -1)
11799 return NULL;
11800 length = PyUnicode_GET_LENGTH(self);
11801 kind = PyUnicode_KIND(self);
11802 data = PyUnicode_DATA(self);
11803
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 if (length == 1)
11806 return PyBool_FromLong(
11807 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011809 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011811 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011812
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 for (i = 0; i < length; i++) {
11815 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011816
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011818 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 else if (!cased && Py_UNICODE_ISUPPER(ch))
11820 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011822 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823}
11824
INADA Naoki3ae20562017-01-16 20:41:20 +090011825/*[clinic input]
11826str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827
INADA Naoki3ae20562017-01-16 20:41:20 +090011828Return True if the string is a title-cased string, False otherwise.
11829
11830In a title-cased string, upper- and title-case characters may only
11831follow uncased characters and lowercase characters only cased ones.
11832[clinic start generated code]*/
11833
11834static PyObject *
11835unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011836/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011838 Py_ssize_t i, length;
11839 int kind;
11840 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841 int cased, previous_is_cased;
11842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 if (PyUnicode_READY(self) == -1)
11844 return NULL;
11845 length = PyUnicode_GET_LENGTH(self);
11846 kind = PyUnicode_KIND(self);
11847 data = PyUnicode_DATA(self);
11848
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 if (length == 1) {
11851 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11852 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11853 (Py_UNICODE_ISUPPER(ch) != 0));
11854 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011856 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011858 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011859
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 cased = 0;
11861 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 for (i = 0; i < length; i++) {
11863 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011864
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11866 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011867 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 previous_is_cased = 1;
11869 cased = 1;
11870 }
11871 else if (Py_UNICODE_ISLOWER(ch)) {
11872 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011873 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 previous_is_cased = 1;
11875 cased = 1;
11876 }
11877 else
11878 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011880 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881}
11882
INADA Naoki3ae20562017-01-16 20:41:20 +090011883/*[clinic input]
11884str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
INADA Naoki3ae20562017-01-16 20:41:20 +090011886Return True if the string is a whitespace string, False otherwise.
11887
11888A string is whitespace if all characters in the string are whitespace and there
11889is at least one character in the string.
11890[clinic start generated code]*/
11891
11892static PyObject *
11893unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011894/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 Py_ssize_t i, length;
11897 int kind;
11898 void *data;
11899
11900 if (PyUnicode_READY(self) == -1)
11901 return NULL;
11902 length = PyUnicode_GET_LENGTH(self);
11903 kind = PyUnicode_KIND(self);
11904 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (length == 1)
11908 return PyBool_FromLong(
11909 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011911 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011913 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 for (i = 0; i < length; i++) {
11916 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011917 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011918 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011920 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921}
11922
INADA Naoki3ae20562017-01-16 20:41:20 +090011923/*[clinic input]
11924str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011925
INADA Naoki3ae20562017-01-16 20:41:20 +090011926Return True if the string is an alphabetic string, False otherwise.
11927
11928A string is alphabetic if all characters in the string are alphabetic and there
11929is at least one character in the string.
11930[clinic start generated code]*/
11931
11932static PyObject *
11933unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011934/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011935{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 Py_ssize_t i, length;
11937 int kind;
11938 void *data;
11939
11940 if (PyUnicode_READY(self) == -1)
11941 return NULL;
11942 length = PyUnicode_GET_LENGTH(self);
11943 kind = PyUnicode_KIND(self);
11944 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011945
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011946 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 if (length == 1)
11948 return PyBool_FromLong(
11949 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011950
11951 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011953 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 for (i = 0; i < length; i++) {
11956 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011957 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011958 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011959 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011960}
11961
INADA Naoki3ae20562017-01-16 20:41:20 +090011962/*[clinic input]
11963str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011964
INADA Naoki3ae20562017-01-16 20:41:20 +090011965Return True if the string is an alpha-numeric string, False otherwise.
11966
11967A string is alpha-numeric if all characters in the string are alpha-numeric and
11968there is at least one character in the string.
11969[clinic start generated code]*/
11970
11971static PyObject *
11972unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011973/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011974{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 int kind;
11976 void *data;
11977 Py_ssize_t len, i;
11978
11979 if (PyUnicode_READY(self) == -1)
11980 return NULL;
11981
11982 kind = PyUnicode_KIND(self);
11983 data = PyUnicode_DATA(self);
11984 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011985
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011986 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 if (len == 1) {
11988 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11989 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11990 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011991
11992 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011993 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011994 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 for (i = 0; i < len; i++) {
11997 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011998 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011999 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012000 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012001 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012002}
12003
INADA Naoki3ae20562017-01-16 20:41:20 +090012004/*[clinic input]
12005str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012006
INADA Naoki3ae20562017-01-16 20:41:20 +090012007Return True if the string is a decimal string, False otherwise.
12008
12009A string is a decimal string if all characters in the string are decimal and
12010there is at least one character in the string.
12011[clinic start generated code]*/
12012
12013static PyObject *
12014unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012015/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012017 Py_ssize_t i, length;
12018 int kind;
12019 void *data;
12020
12021 if (PyUnicode_READY(self) == -1)
12022 return NULL;
12023 length = PyUnicode_GET_LENGTH(self);
12024 kind = PyUnicode_KIND(self);
12025 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012026
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028 if (length == 1)
12029 return PyBool_FromLong(
12030 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012032 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012034 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 for (i = 0; i < length; i++) {
12037 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012038 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012040 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041}
12042
INADA Naoki3ae20562017-01-16 20:41:20 +090012043/*[clinic input]
12044str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045
INADA Naoki3ae20562017-01-16 20:41:20 +090012046Return True if the string is a digit string, False otherwise.
12047
12048A string is a digit string if all characters in the string are digits and there
12049is at least one character in the string.
12050[clinic start generated code]*/
12051
12052static PyObject *
12053unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012054/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056 Py_ssize_t i, length;
12057 int kind;
12058 void *data;
12059
12060 if (PyUnicode_READY(self) == -1)
12061 return NULL;
12062 length = PyUnicode_GET_LENGTH(self);
12063 kind = PyUnicode_KIND(self);
12064 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 if (length == 1) {
12068 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12069 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12070 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012072 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012074 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012076 for (i = 0; i < length; i++) {
12077 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012078 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012080 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081}
12082
INADA Naoki3ae20562017-01-16 20:41:20 +090012083/*[clinic input]
12084str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012085
INADA Naoki3ae20562017-01-16 20:41:20 +090012086Return True if the string is a numeric string, False otherwise.
12087
12088A string is numeric if all characters in the string are numeric and there is at
12089least one character in the string.
12090[clinic start generated code]*/
12091
12092static PyObject *
12093unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012094/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 Py_ssize_t i, length;
12097 int kind;
12098 void *data;
12099
12100 if (PyUnicode_READY(self) == -1)
12101 return NULL;
12102 length = PyUnicode_GET_LENGTH(self);
12103 kind = PyUnicode_KIND(self);
12104 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 if (length == 1)
12108 return PyBool_FromLong(
12109 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012111 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012113 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 for (i = 0; i < length; i++) {
12116 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012117 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012119 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120}
12121
Martin v. Löwis47383402007-08-15 07:32:56 +000012122int
12123PyUnicode_IsIdentifier(PyObject *self)
12124{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 int kind;
12126 void *data;
12127 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012128 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 if (PyUnicode_READY(self) == -1) {
12131 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012132 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 }
12134
12135 /* Special case for empty strings */
12136 if (PyUnicode_GET_LENGTH(self) == 0)
12137 return 0;
12138 kind = PyUnicode_KIND(self);
12139 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012140
12141 /* PEP 3131 says that the first character must be in
12142 XID_Start and subsequent characters in XID_Continue,
12143 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012144 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012145 letters, digits, underscore). However, given the current
12146 definition of XID_Start and XID_Continue, it is sufficient
12147 to check just for these, except that _ must be allowed
12148 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012150 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012151 return 0;
12152
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012153 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012155 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012156 return 1;
12157}
12158
INADA Naoki3ae20562017-01-16 20:41:20 +090012159/*[clinic input]
12160str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012161
INADA Naoki3ae20562017-01-16 20:41:20 +090012162Return True if the string is a valid Python identifier, False otherwise.
12163
12164Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12165"class".
12166[clinic start generated code]*/
12167
12168static PyObject *
12169unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012170/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012171{
12172 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12173}
12174
INADA Naoki3ae20562017-01-16 20:41:20 +090012175/*[clinic input]
12176str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012177
INADA Naoki3ae20562017-01-16 20:41:20 +090012178Return True if the string is printable, False otherwise.
12179
12180A string is printable if all of its characters are considered printable in
12181repr() or if it is empty.
12182[clinic start generated code]*/
12183
12184static PyObject *
12185unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012186/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012187{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188 Py_ssize_t i, length;
12189 int kind;
12190 void *data;
12191
12192 if (PyUnicode_READY(self) == -1)
12193 return NULL;
12194 length = PyUnicode_GET_LENGTH(self);
12195 kind = PyUnicode_KIND(self);
12196 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012197
12198 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 if (length == 1)
12200 return PyBool_FromLong(
12201 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 for (i = 0; i < length; i++) {
12204 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012205 Py_RETURN_FALSE;
12206 }
12207 }
12208 Py_RETURN_TRUE;
12209}
12210
INADA Naoki3ae20562017-01-16 20:41:20 +090012211/*[clinic input]
12212str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
INADA Naoki3ae20562017-01-16 20:41:20 +090012214 iterable: object
12215 /
12216
12217Concatenate any number of strings.
12218
Martin Panter91a88662017-01-24 00:30:06 +000012219The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012220The result is returned as a new string.
12221
12222Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12223[clinic start generated code]*/
12224
12225static PyObject *
12226unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012227/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228{
INADA Naoki3ae20562017-01-16 20:41:20 +090012229 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230}
12231
Martin v. Löwis18e16552006-02-15 17:27:45 +000012232static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012233unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 if (PyUnicode_READY(self) == -1)
12236 return -1;
12237 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238}
12239
INADA Naoki3ae20562017-01-16 20:41:20 +090012240/*[clinic input]
12241str.ljust as unicode_ljust
12242
12243 width: Py_ssize_t
12244 fillchar: Py_UCS4 = ' '
12245 /
12246
12247Return a left-justified string of length width.
12248
12249Padding is done using the specified fill character (default is a space).
12250[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
12252static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012253unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12254/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012256 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258
Victor Stinnerc4b49542011-12-11 22:44:26 +010012259 if (PyUnicode_GET_LENGTH(self) >= width)
12260 return unicode_result_unchanged(self);
12261
12262 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263}
12264
INADA Naoki3ae20562017-01-16 20:41:20 +090012265/*[clinic input]
12266str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267
INADA Naoki3ae20562017-01-16 20:41:20 +090012268Return a copy of the string converted to lowercase.
12269[clinic start generated code]*/
12270
12271static PyObject *
12272unicode_lower_impl(PyObject *self)
12273/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012275 if (PyUnicode_READY(self) == -1)
12276 return NULL;
12277 if (PyUnicode_IS_ASCII(self))
12278 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012279 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280}
12281
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012282#define LEFTSTRIP 0
12283#define RIGHTSTRIP 1
12284#define BOTHSTRIP 2
12285
12286/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012287static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012288
INADA Naoki3ae20562017-01-16 20:41:20 +090012289#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012290
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012291/* externally visible for str.strip(unicode) */
12292PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012293_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012294{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 void *data;
12296 int kind;
12297 Py_ssize_t i, j, len;
12298 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012299 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12302 return NULL;
12303
12304 kind = PyUnicode_KIND(self);
12305 data = PyUnicode_DATA(self);
12306 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012307 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12309 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012310 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012311
Benjamin Peterson14339b62009-01-31 16:36:08 +000012312 i = 0;
12313 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012314 while (i < len) {
12315 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12316 if (!BLOOM(sepmask, ch))
12317 break;
12318 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12319 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012320 i++;
12321 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012323
Benjamin Peterson14339b62009-01-31 16:36:08 +000012324 j = len;
12325 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012326 j--;
12327 while (j >= i) {
12328 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12329 if (!BLOOM(sepmask, ch))
12330 break;
12331 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12332 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012333 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012334 }
12335
Benjamin Peterson29060642009-01-31 22:14:21 +000012336 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012337 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012338
Victor Stinner7931d9a2011-11-04 00:22:48 +010012339 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340}
12341
12342PyObject*
12343PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12344{
12345 unsigned char *data;
12346 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012347 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348
Victor Stinnerde636f32011-10-01 03:55:54 +020012349 if (PyUnicode_READY(self) == -1)
12350 return NULL;
12351
Victor Stinner684d5fd2012-05-03 02:32:34 +020012352 length = PyUnicode_GET_LENGTH(self);
12353 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012354
Victor Stinner684d5fd2012-05-03 02:32:34 +020012355 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012356 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357
Victor Stinnerde636f32011-10-01 03:55:54 +020012358 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012359 PyErr_SetString(PyExc_IndexError, "string index out of range");
12360 return NULL;
12361 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012362 if (start >= length || end < start)
12363 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012364
Victor Stinner684d5fd2012-05-03 02:32:34 +020012365 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012366 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012367 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012368 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012369 }
12370 else {
12371 kind = PyUnicode_KIND(self);
12372 data = PyUnicode_1BYTE_DATA(self);
12373 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012374 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012375 length);
12376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378
12379static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012380do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012381{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 Py_ssize_t len, i, j;
12383
12384 if (PyUnicode_READY(self) == -1)
12385 return NULL;
12386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012388
Victor Stinnercc7af722013-04-09 22:39:24 +020012389 if (PyUnicode_IS_ASCII(self)) {
12390 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12391
12392 i = 0;
12393 if (striptype != RIGHTSTRIP) {
12394 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012395 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012396 if (!_Py_ascii_whitespace[ch])
12397 break;
12398 i++;
12399 }
12400 }
12401
12402 j = len;
12403 if (striptype != LEFTSTRIP) {
12404 j--;
12405 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012406 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012407 if (!_Py_ascii_whitespace[ch])
12408 break;
12409 j--;
12410 }
12411 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012412 }
12413 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012414 else {
12415 int kind = PyUnicode_KIND(self);
12416 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012417
Victor Stinnercc7af722013-04-09 22:39:24 +020012418 i = 0;
12419 if (striptype != RIGHTSTRIP) {
12420 while (i < len) {
12421 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12422 if (!Py_UNICODE_ISSPACE(ch))
12423 break;
12424 i++;
12425 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012426 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012427
12428 j = len;
12429 if (striptype != LEFTSTRIP) {
12430 j--;
12431 while (j >= i) {
12432 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12433 if (!Py_UNICODE_ISSPACE(ch))
12434 break;
12435 j--;
12436 }
12437 j++;
12438 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012439 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012440
Victor Stinner7931d9a2011-11-04 00:22:48 +010012441 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442}
12443
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012444
12445static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012446do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012447{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012448 if (sep != NULL && sep != Py_None) {
12449 if (PyUnicode_Check(sep))
12450 return _PyUnicode_XStrip(self, striptype, sep);
12451 else {
12452 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012453 "%s arg must be None or str",
12454 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012455 return NULL;
12456 }
12457 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012458
Benjamin Peterson14339b62009-01-31 16:36:08 +000012459 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012460}
12461
12462
INADA Naoki3ae20562017-01-16 20:41:20 +090012463/*[clinic input]
12464str.strip as unicode_strip
12465
12466 chars: object = None
12467 /
12468
Victor Stinner0c4a8282017-01-17 02:21:47 +010012469Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012470
12471If chars is given and not None, remove characters in chars instead.
12472[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012473
12474static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012475unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012476/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012477{
INADA Naoki3ae20562017-01-16 20:41:20 +090012478 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012479}
12480
12481
INADA Naoki3ae20562017-01-16 20:41:20 +090012482/*[clinic input]
12483str.lstrip as unicode_lstrip
12484
12485 chars: object = NULL
12486 /
12487
12488Return a copy of the string with leading whitespace removed.
12489
12490If chars is given and not None, remove characters in chars instead.
12491[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012492
12493static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012494unicode_lstrip_impl(PyObject *self, PyObject *chars)
12495/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012496{
INADA Naoki3ae20562017-01-16 20:41:20 +090012497 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012498}
12499
12500
INADA Naoki3ae20562017-01-16 20:41:20 +090012501/*[clinic input]
12502str.rstrip as unicode_rstrip
12503
12504 chars: object = NULL
12505 /
12506
12507Return a copy of the string with trailing whitespace removed.
12508
12509If chars is given and not None, remove characters in chars instead.
12510[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012511
12512static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012513unicode_rstrip_impl(PyObject *self, PyObject *chars)
12514/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012515{
INADA Naoki3ae20562017-01-16 20:41:20 +090012516 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012517}
12518
12519
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012521unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012523 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012524 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525
Serhiy Storchaka05997252013-01-26 12:14:02 +020012526 if (len < 1)
12527 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528
Victor Stinnerc4b49542011-12-11 22:44:26 +010012529 /* no repeat, return original string */
12530 if (len == 1)
12531 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012532
Benjamin Petersonbac79492012-01-14 13:34:47 -050012533 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 return NULL;
12535
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012536 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012537 PyErr_SetString(PyExc_OverflowError,
12538 "repeated string is too long");
12539 return NULL;
12540 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012542
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012543 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544 if (!u)
12545 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012546 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 if (PyUnicode_GET_LENGTH(str) == 1) {
12549 const int kind = PyUnicode_KIND(str);
12550 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012551 if (kind == PyUnicode_1BYTE_KIND) {
12552 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012553 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012554 }
12555 else if (kind == PyUnicode_2BYTE_KIND) {
12556 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012557 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012558 ucs2[n] = fill_char;
12559 } else {
12560 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12561 assert(kind == PyUnicode_4BYTE_KIND);
12562 for (n = 0; n < len; ++n)
12563 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 }
12566 else {
12567 /* number of characters copied this far */
12568 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012569 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012571 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012573 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012575 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012576 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578 }
12579
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012580 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012581 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012582}
12583
Alexander Belopolsky40018472011-02-26 01:02:56 +000012584PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012585PyUnicode_Replace(PyObject *str,
12586 PyObject *substr,
12587 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012588 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012590 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12591 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012592 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012593 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594}
12595
INADA Naoki3ae20562017-01-16 20:41:20 +090012596/*[clinic input]
12597str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598
INADA Naoki3ae20562017-01-16 20:41:20 +090012599 old: unicode
12600 new: unicode
12601 count: Py_ssize_t = -1
12602 Maximum number of occurrences to replace.
12603 -1 (the default value) means replace all occurrences.
12604 /
12605
12606Return a copy with all occurrences of substring old replaced by new.
12607
12608If the optional argument count is given, only the first count occurrences are
12609replaced.
12610[clinic start generated code]*/
12611
12612static PyObject *
12613unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12614 Py_ssize_t count)
12615/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012617 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012618 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012619 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620}
12621
Alexander Belopolsky40018472011-02-26 01:02:56 +000012622static PyObject *
12623unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012625 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 Py_ssize_t isize;
12627 Py_ssize_t osize, squote, dquote, i, o;
12628 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012629 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012633 return NULL;
12634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635 isize = PyUnicode_GET_LENGTH(unicode);
12636 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012638 /* Compute length of output, quote characters, and
12639 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012640 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012641 max = 127;
12642 squote = dquote = 0;
12643 ikind = PyUnicode_KIND(unicode);
12644 for (i = 0; i < isize; i++) {
12645 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012646 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012648 case '\'': squote++; break;
12649 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012651 incr = 2;
12652 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 default:
12654 /* Fast-path ASCII */
12655 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012656 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012658 ;
12659 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012662 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012663 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012664 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012665 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012666 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012668 if (osize > PY_SSIZE_T_MAX - incr) {
12669 PyErr_SetString(PyExc_OverflowError,
12670 "string is too long to generate repr");
12671 return NULL;
12672 }
12673 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 }
12675
12676 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012677 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012679 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 if (dquote)
12681 /* Both squote and dquote present. Use squote,
12682 and escape them */
12683 osize += squote;
12684 else
12685 quote = '"';
12686 }
Victor Stinner55c08782013-04-14 18:45:39 +020012687 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688
12689 repr = PyUnicode_New(osize, max);
12690 if (repr == NULL)
12691 return NULL;
12692 okind = PyUnicode_KIND(repr);
12693 odata = PyUnicode_DATA(repr);
12694
12695 PyUnicode_WRITE(okind, odata, 0, quote);
12696 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012697 if (unchanged) {
12698 _PyUnicode_FastCopyCharacters(repr, 1,
12699 unicode, 0,
12700 isize);
12701 }
12702 else {
12703 for (i = 0, o = 1; i < isize; i++) {
12704 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705
Victor Stinner55c08782013-04-14 18:45:39 +020012706 /* Escape quotes and backslashes */
12707 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012708 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012710 continue;
12711 }
12712
12713 /* Map special whitespace to '\t', \n', '\r' */
12714 if (ch == '\t') {
12715 PyUnicode_WRITE(okind, odata, o++, '\\');
12716 PyUnicode_WRITE(okind, odata, o++, 't');
12717 }
12718 else if (ch == '\n') {
12719 PyUnicode_WRITE(okind, odata, o++, '\\');
12720 PyUnicode_WRITE(okind, odata, o++, 'n');
12721 }
12722 else if (ch == '\r') {
12723 PyUnicode_WRITE(okind, odata, o++, '\\');
12724 PyUnicode_WRITE(okind, odata, o++, 'r');
12725 }
12726
12727 /* Map non-printable US ASCII to '\xhh' */
12728 else if (ch < ' ' || ch == 0x7F) {
12729 PyUnicode_WRITE(okind, odata, o++, '\\');
12730 PyUnicode_WRITE(okind, odata, o++, 'x');
12731 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12732 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12733 }
12734
12735 /* Copy ASCII characters as-is */
12736 else if (ch < 0x7F) {
12737 PyUnicode_WRITE(okind, odata, o++, ch);
12738 }
12739
12740 /* Non-ASCII characters */
12741 else {
12742 /* Map Unicode whitespace and control characters
12743 (categories Z* and C* except ASCII space)
12744 */
12745 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12746 PyUnicode_WRITE(okind, odata, o++, '\\');
12747 /* Map 8-bit characters to '\xhh' */
12748 if (ch <= 0xff) {
12749 PyUnicode_WRITE(okind, odata, o++, 'x');
12750 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12751 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12752 }
12753 /* Map 16-bit characters to '\uxxxx' */
12754 else if (ch <= 0xffff) {
12755 PyUnicode_WRITE(okind, odata, o++, 'u');
12756 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12757 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12758 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12759 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12760 }
12761 /* Map 21-bit characters to '\U00xxxxxx' */
12762 else {
12763 PyUnicode_WRITE(okind, odata, o++, 'U');
12764 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12765 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12766 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12767 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12768 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12769 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12770 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12771 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12772 }
12773 }
12774 /* Copy characters as-is */
12775 else {
12776 PyUnicode_WRITE(okind, odata, o++, ch);
12777 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012778 }
12779 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012780 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012782 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012783 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784}
12785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012786PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012787 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788\n\
12789Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012790such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791arguments start and end are interpreted as in slice notation.\n\
12792\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012793Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794
12795static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012796unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012798 /* initialize variables to prevent gcc warning */
12799 PyObject *substring = NULL;
12800 Py_ssize_t start = 0;
12801 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012804 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012805 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012807 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012810 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012812 if (result == -2)
12813 return NULL;
12814
Christian Heimes217cfd12007-12-02 14:31:20 +000012815 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816}
12817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012818PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012819 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012821Return the highest index in S where substring sub is found,\n\
12822such that sub is contained within S[start:end]. Optional\n\
12823arguments start and end are interpreted as in slice notation.\n\
12824\n\
12825Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012826
12827static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012828unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012830 /* initialize variables to prevent gcc warning */
12831 PyObject *substring = NULL;
12832 Py_ssize_t start = 0;
12833 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012834 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012835
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012836 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012837 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012839 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012840 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012842 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 if (result == -2)
12845 return NULL;
12846
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847 if (result < 0) {
12848 PyErr_SetString(PyExc_ValueError, "substring not found");
12849 return NULL;
12850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851
Christian Heimes217cfd12007-12-02 14:31:20 +000012852 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853}
12854
INADA Naoki3ae20562017-01-16 20:41:20 +090012855/*[clinic input]
12856str.rjust as unicode_rjust
12857
12858 width: Py_ssize_t
12859 fillchar: Py_UCS4 = ' '
12860 /
12861
12862Return a right-justified string of length width.
12863
12864Padding is done using the specified fill character (default is a space).
12865[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866
12867static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012868unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12869/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012870{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012871 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872 return NULL;
12873
Victor Stinnerc4b49542011-12-11 22:44:26 +010012874 if (PyUnicode_GET_LENGTH(self) >= width)
12875 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012876
Victor Stinnerc4b49542011-12-11 22:44:26 +010012877 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878}
12879
Alexander Belopolsky40018472011-02-26 01:02:56 +000012880PyObject *
12881PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012883 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012886 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887}
12888
INADA Naoki3ae20562017-01-16 20:41:20 +090012889/*[clinic input]
12890str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891
INADA Naoki3ae20562017-01-16 20:41:20 +090012892 sep: object = None
12893 The delimiter according which to split the string.
12894 None (the default value) means split according to any whitespace,
12895 and discard empty strings from the result.
12896 maxsplit: Py_ssize_t = -1
12897 Maximum number of splits to do.
12898 -1 (the default value) means no limit.
12899
12900Return a list of the words in the string, using sep as the delimiter string.
12901[clinic start generated code]*/
12902
12903static PyObject *
12904unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12905/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906{
INADA Naoki3ae20562017-01-16 20:41:20 +090012907 if (sep == Py_None)
12908 return split(self, NULL, maxsplit);
12909 if (PyUnicode_Check(sep))
12910 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012911
12912 PyErr_Format(PyExc_TypeError,
12913 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012914 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012915 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012916}
12917
Thomas Wouters477c8d52006-05-27 19:21:47 +000012918PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012919PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012920{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012921 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012922 int kind1, kind2;
12923 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012925
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012926 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012927 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012928
Victor Stinner14f8f022011-10-05 20:58:25 +020012929 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012930 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012931 len1 = PyUnicode_GET_LENGTH(str_obj);
12932 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012933 if (kind1 < kind2 || len1 < len2) {
12934 _Py_INCREF_UNICODE_EMPTY();
12935 if (!unicode_empty)
12936 out = NULL;
12937 else {
12938 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12939 Py_DECREF(unicode_empty);
12940 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012941 return out;
12942 }
12943 buf1 = PyUnicode_DATA(str_obj);
12944 buf2 = PyUnicode_DATA(sep_obj);
12945 if (kind2 != kind1) {
12946 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12947 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012948 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012950
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012951 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012952 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012953 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12954 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12955 else
12956 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012957 break;
12958 case PyUnicode_2BYTE_KIND:
12959 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12960 break;
12961 case PyUnicode_4BYTE_KIND:
12962 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12963 break;
12964 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012965 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012967
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012968 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012969 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970
12971 return out;
12972}
12973
12974
12975PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012976PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012977{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012979 int kind1, kind2;
12980 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012982
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012983 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012984 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012985
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012986 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012988 len1 = PyUnicode_GET_LENGTH(str_obj);
12989 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012990 if (kind1 < kind2 || len1 < len2) {
12991 _Py_INCREF_UNICODE_EMPTY();
12992 if (!unicode_empty)
12993 out = NULL;
12994 else {
12995 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12996 Py_DECREF(unicode_empty);
12997 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012998 return out;
12999 }
13000 buf1 = PyUnicode_DATA(str_obj);
13001 buf2 = PyUnicode_DATA(sep_obj);
13002 if (kind2 != kind1) {
13003 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13004 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013005 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013006 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013008 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013009 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013010 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13011 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13012 else
13013 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014 break;
13015 case PyUnicode_2BYTE_KIND:
13016 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13017 break;
13018 case PyUnicode_4BYTE_KIND:
13019 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13020 break;
13021 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013022 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013024
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013025 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013027
13028 return out;
13029}
13030
INADA Naoki3ae20562017-01-16 20:41:20 +090013031/*[clinic input]
13032str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013033
INADA Naoki3ae20562017-01-16 20:41:20 +090013034 sep: object
13035 /
13036
13037Partition the string into three parts using the given separator.
13038
13039This will search for the separator in the string. If the separator is found,
13040returns a 3-tuple containing the part before the separator, the separator
13041itself, and the part after it.
13042
13043If the separator is not found, returns a 3-tuple containing the original string
13044and two empty strings.
13045[clinic start generated code]*/
13046
13047static PyObject *
13048unicode_partition(PyObject *self, PyObject *sep)
13049/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013050{
INADA Naoki3ae20562017-01-16 20:41:20 +090013051 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013052}
13053
INADA Naoki3ae20562017-01-16 20:41:20 +090013054/*[clinic input]
13055str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013056
INADA Naoki3ae20562017-01-16 20:41:20 +090013057Partition the string into three parts using the given separator.
13058
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013059This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013060the separator is found, returns a 3-tuple containing the part before the
13061separator, the separator itself, and the part after it.
13062
13063If the separator is not found, returns a 3-tuple containing two empty strings
13064and the original string.
13065[clinic start generated code]*/
13066
13067static PyObject *
13068unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013069/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013070{
INADA Naoki3ae20562017-01-16 20:41:20 +090013071 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013072}
13073
Alexander Belopolsky40018472011-02-26 01:02:56 +000013074PyObject *
13075PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013076{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013077 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013078 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013079
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013080 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013081}
13082
INADA Naoki3ae20562017-01-16 20:41:20 +090013083/*[clinic input]
13084str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013085
INADA Naoki3ae20562017-01-16 20:41:20 +090013086Return a list of the words in the string, using sep as the delimiter string.
13087
13088Splits are done starting at the end of the string and working to the front.
13089[clinic start generated code]*/
13090
13091static PyObject *
13092unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13093/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013094{
INADA Naoki3ae20562017-01-16 20:41:20 +090013095 if (sep == Py_None)
13096 return rsplit(self, NULL, maxsplit);
13097 if (PyUnicode_Check(sep))
13098 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013099
13100 PyErr_Format(PyExc_TypeError,
13101 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013102 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013103 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013104}
13105
INADA Naoki3ae20562017-01-16 20:41:20 +090013106/*[clinic input]
13107str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013109 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013110
13111Return a list of the lines in the string, breaking at line boundaries.
13112
13113Line breaks are not included in the resulting list unless keepends is given and
13114true.
13115[clinic start generated code]*/
13116
13117static PyObject *
13118unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013119/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013121 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122}
13123
13124static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013125PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013127 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128}
13129
INADA Naoki3ae20562017-01-16 20:41:20 +090013130/*[clinic input]
13131str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132
INADA Naoki3ae20562017-01-16 20:41:20 +090013133Convert uppercase characters to lowercase and lowercase characters to uppercase.
13134[clinic start generated code]*/
13135
13136static PyObject *
13137unicode_swapcase_impl(PyObject *self)
13138/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013139{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013140 if (PyUnicode_READY(self) == -1)
13141 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013142 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143}
13144
Larry Hastings61272b72014-01-07 12:41:53 -080013145/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013146
Larry Hastings31826802013-10-19 00:09:25 -070013147@staticmethod
13148str.maketrans as unicode_maketrans
13149
13150 x: object
13151
13152 y: unicode=NULL
13153
13154 z: unicode=NULL
13155
13156 /
13157
13158Return a translation table usable for str.translate().
13159
13160If there is only one argument, it must be a dictionary mapping Unicode
13161ordinals (integers) or characters to Unicode ordinals, strings or None.
13162Character keys will be then converted to ordinals.
13163If there are two arguments, they must be strings of equal length, and
13164in the resulting dictionary, each character in x will be mapped to the
13165character at the same position in y. If there is a third argument, it
13166must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013167[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013168
Larry Hastings31826802013-10-19 00:09:25 -070013169static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013170unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013171/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013172{
Georg Brandlceee0772007-11-27 23:48:05 +000013173 PyObject *new = NULL, *key, *value;
13174 Py_ssize_t i = 0;
13175 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013176
Georg Brandlceee0772007-11-27 23:48:05 +000013177 new = PyDict_New();
13178 if (!new)
13179 return NULL;
13180 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013181 int x_kind, y_kind, z_kind;
13182 void *x_data, *y_data, *z_data;
13183
Georg Brandlceee0772007-11-27 23:48:05 +000013184 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013185 if (!PyUnicode_Check(x)) {
13186 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13187 "be a string if there is a second argument");
13188 goto err;
13189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013190 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013191 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13192 "arguments must have equal length");
13193 goto err;
13194 }
13195 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013196 x_kind = PyUnicode_KIND(x);
13197 y_kind = PyUnicode_KIND(y);
13198 x_data = PyUnicode_DATA(x);
13199 y_data = PyUnicode_DATA(y);
13200 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13201 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013202 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013203 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013204 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013205 if (!value) {
13206 Py_DECREF(key);
13207 goto err;
13208 }
Georg Brandlceee0772007-11-27 23:48:05 +000013209 res = PyDict_SetItem(new, key, value);
13210 Py_DECREF(key);
13211 Py_DECREF(value);
13212 if (res < 0)
13213 goto err;
13214 }
13215 /* create entries for deleting chars in z */
13216 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013217 z_kind = PyUnicode_KIND(z);
13218 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013219 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013220 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013221 if (!key)
13222 goto err;
13223 res = PyDict_SetItem(new, key, Py_None);
13224 Py_DECREF(key);
13225 if (res < 0)
13226 goto err;
13227 }
13228 }
13229 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013230 int kind;
13231 void *data;
13232
Georg Brandlceee0772007-11-27 23:48:05 +000013233 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013234 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013235 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13236 "to maketrans it must be a dict");
13237 goto err;
13238 }
13239 /* copy entries into the new dict, converting string keys to int keys */
13240 while (PyDict_Next(x, &i, &key, &value)) {
13241 if (PyUnicode_Check(key)) {
13242 /* convert string keys to integer keys */
13243 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013244 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013245 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13246 "table must be of length 1");
13247 goto err;
13248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013249 kind = PyUnicode_KIND(key);
13250 data = PyUnicode_DATA(key);
13251 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013252 if (!newkey)
13253 goto err;
13254 res = PyDict_SetItem(new, newkey, value);
13255 Py_DECREF(newkey);
13256 if (res < 0)
13257 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013258 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013259 /* just keep integer keys */
13260 if (PyDict_SetItem(new, key, value) < 0)
13261 goto err;
13262 } else {
13263 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13264 "be strings or integers");
13265 goto err;
13266 }
13267 }
13268 }
13269 return new;
13270 err:
13271 Py_DECREF(new);
13272 return NULL;
13273}
13274
INADA Naoki3ae20562017-01-16 20:41:20 +090013275/*[clinic input]
13276str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277
INADA Naoki3ae20562017-01-16 20:41:20 +090013278 table: object
13279 Translation table, which must be a mapping of Unicode ordinals to
13280 Unicode ordinals, strings, or None.
13281 /
13282
13283Replace each character in the string using the given translation table.
13284
13285The table must implement lookup/indexing via __getitem__, for instance a
13286dictionary or list. If this operation raises LookupError, the character is
13287left untouched. Characters mapped to None are deleted.
13288[clinic start generated code]*/
13289
13290static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013292/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013294 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295}
13296
INADA Naoki3ae20562017-01-16 20:41:20 +090013297/*[clinic input]
13298str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013299
INADA Naoki3ae20562017-01-16 20:41:20 +090013300Return a copy of the string converted to uppercase.
13301[clinic start generated code]*/
13302
13303static PyObject *
13304unicode_upper_impl(PyObject *self)
13305/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013307 if (PyUnicode_READY(self) == -1)
13308 return NULL;
13309 if (PyUnicode_IS_ASCII(self))
13310 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013311 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013312}
13313
INADA Naoki3ae20562017-01-16 20:41:20 +090013314/*[clinic input]
13315str.zfill as unicode_zfill
13316
13317 width: Py_ssize_t
13318 /
13319
13320Pad a numeric string with zeros on the left, to fill a field of the given width.
13321
13322The string is never truncated.
13323[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013324
13325static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013326unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013327/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013328{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013329 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013330 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013331 int kind;
13332 void *data;
13333 Py_UCS4 chr;
13334
Benjamin Petersonbac79492012-01-14 13:34:47 -050013335 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013336 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337
Victor Stinnerc4b49542011-12-11 22:44:26 +010013338 if (PyUnicode_GET_LENGTH(self) >= width)
13339 return unicode_result_unchanged(self);
13340
13341 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342
13343 u = pad(self, fill, 0, '0');
13344
Walter Dörwald068325e2002-04-15 13:36:47 +000013345 if (u == NULL)
13346 return NULL;
13347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013348 kind = PyUnicode_KIND(u);
13349 data = PyUnicode_DATA(u);
13350 chr = PyUnicode_READ(kind, data, fill);
13351
13352 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013354 PyUnicode_WRITE(kind, data, 0, chr);
13355 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356 }
13357
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013358 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013359 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361
13362#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013363static PyObject *
13364unicode__decimal2ascii(PyObject *self)
13365{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013366 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013367}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013368#endif
13369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013370PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013372\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013373Return True if S starts with the specified prefix, False otherwise.\n\
13374With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013375With optional end, stop comparing S at that position.\n\
13376prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013377
13378static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013379unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013381{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013382 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013383 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013384 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013385 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013386 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013387
Jesus Ceaac451502011-04-20 17:09:23 +020013388 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013389 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013390 if (PyTuple_Check(subobj)) {
13391 Py_ssize_t i;
13392 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013393 substring = PyTuple_GET_ITEM(subobj, i);
13394 if (!PyUnicode_Check(substring)) {
13395 PyErr_Format(PyExc_TypeError,
13396 "tuple for startswith must only contain str, "
13397 "not %.100s",
13398 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013399 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013400 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013401 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013402 if (result == -1)
13403 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013404 if (result) {
13405 Py_RETURN_TRUE;
13406 }
13407 }
13408 /* nothing matched */
13409 Py_RETURN_FALSE;
13410 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013411 if (!PyUnicode_Check(subobj)) {
13412 PyErr_Format(PyExc_TypeError,
13413 "startswith first arg must be str or "
13414 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013415 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013416 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013417 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013418 if (result == -1)
13419 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013420 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421}
13422
13423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013424PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013427Return True if S ends with the specified suffix, False otherwise.\n\
13428With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013429With optional end, stop comparing S at that position.\n\
13430suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013431
13432static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013433unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013434 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013435{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013436 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013437 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013438 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013439 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013440 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013441
Jesus Ceaac451502011-04-20 17:09:23 +020013442 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013444 if (PyTuple_Check(subobj)) {
13445 Py_ssize_t i;
13446 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013447 substring = PyTuple_GET_ITEM(subobj, i);
13448 if (!PyUnicode_Check(substring)) {
13449 PyErr_Format(PyExc_TypeError,
13450 "tuple for endswith must only contain str, "
13451 "not %.100s",
13452 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013453 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013454 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013455 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013456 if (result == -1)
13457 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013458 if (result) {
13459 Py_RETURN_TRUE;
13460 }
13461 }
13462 Py_RETURN_FALSE;
13463 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013464 if (!PyUnicode_Check(subobj)) {
13465 PyErr_Format(PyExc_TypeError,
13466 "endswith first arg must be str or "
13467 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013468 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013469 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013470 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013471 if (result == -1)
13472 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013473 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013474}
13475
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013476static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013477_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013478{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013479 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13480 writer->data = PyUnicode_DATA(writer->buffer);
13481
13482 if (!writer->readonly) {
13483 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013484 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013485 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013486 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013487 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13488 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13489 writer->kind = PyUnicode_WCHAR_KIND;
13490 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13491
Victor Stinner8f674cc2013-04-17 23:02:17 +020013492 /* Copy-on-write mode: set buffer size to 0 so
13493 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13494 * next write. */
13495 writer->size = 0;
13496 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013497}
13498
Victor Stinnerd3f08822012-05-29 12:57:52 +020013499void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013500_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013501{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013503
13504 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013505 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013506
13507 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13508 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13509 writer->kind = PyUnicode_WCHAR_KIND;
13510 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013511}
13512
Victor Stinnerd3f08822012-05-29 12:57:52 +020013513int
13514_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13515 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013516{
13517 Py_ssize_t newlen;
13518 PyObject *newbuffer;
13519
Victor Stinner2740e462016-09-06 16:58:36 -070013520 assert(maxchar <= MAX_UNICODE);
13521
Victor Stinnerca9381e2015-09-22 00:58:32 +020013522 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013523 assert((maxchar > writer->maxchar && length >= 0)
13524 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013525
Victor Stinner202fdca2012-05-07 12:47:02 +020013526 if (length > PY_SSIZE_T_MAX - writer->pos) {
13527 PyErr_NoMemory();
13528 return -1;
13529 }
13530 newlen = writer->pos + length;
13531
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013532 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013533
Victor Stinnerd3f08822012-05-29 12:57:52 +020013534 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013535 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013536 if (writer->overallocate
13537 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13538 /* overallocate to limit the number of realloc() */
13539 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013540 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013541 if (newlen < writer->min_length)
13542 newlen = writer->min_length;
13543
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 writer->buffer = PyUnicode_New(newlen, maxchar);
13545 if (writer->buffer == NULL)
13546 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013548 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013549 if (writer->overallocate
13550 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13551 /* overallocate to limit the number of realloc() */
13552 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013553 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013554 if (newlen < writer->min_length)
13555 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013556
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013557 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013558 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013559 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013560 newbuffer = PyUnicode_New(newlen, maxchar);
13561 if (newbuffer == NULL)
13562 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013563 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13564 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013565 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013566 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013567 }
13568 else {
13569 newbuffer = resize_compact(writer->buffer, newlen);
13570 if (newbuffer == NULL)
13571 return -1;
13572 }
13573 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013574 }
13575 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013576 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013577 newbuffer = PyUnicode_New(writer->size, maxchar);
13578 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013579 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013580 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13581 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013582 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013583 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013584 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013585 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013586
13587#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013588}
13589
Victor Stinnerca9381e2015-09-22 00:58:32 +020013590int
13591_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13592 enum PyUnicode_Kind kind)
13593{
13594 Py_UCS4 maxchar;
13595
13596 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13597 assert(writer->kind < kind);
13598
13599 switch (kind)
13600 {
13601 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13602 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13603 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13604 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013605 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013606 }
13607
13608 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13609}
13610
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013611static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013612_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013613{
Victor Stinner2740e462016-09-06 16:58:36 -070013614 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013615 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13616 return -1;
13617 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13618 writer->pos++;
13619 return 0;
13620}
13621
13622int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013623_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13624{
13625 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13626}
13627
13628int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013629_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13630{
13631 Py_UCS4 maxchar;
13632 Py_ssize_t len;
13633
13634 if (PyUnicode_READY(str) == -1)
13635 return -1;
13636 len = PyUnicode_GET_LENGTH(str);
13637 if (len == 0)
13638 return 0;
13639 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13640 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013641 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013642 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013643 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013644 Py_INCREF(str);
13645 writer->buffer = str;
13646 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013647 writer->pos += len;
13648 return 0;
13649 }
13650 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13651 return -1;
13652 }
13653 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13654 str, 0, len);
13655 writer->pos += len;
13656 return 0;
13657}
13658
Victor Stinnere215d962012-10-06 23:03:36 +020013659int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013660_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13661 Py_ssize_t start, Py_ssize_t end)
13662{
13663 Py_UCS4 maxchar;
13664 Py_ssize_t len;
13665
13666 if (PyUnicode_READY(str) == -1)
13667 return -1;
13668
13669 assert(0 <= start);
13670 assert(end <= PyUnicode_GET_LENGTH(str));
13671 assert(start <= end);
13672
13673 if (end == 0)
13674 return 0;
13675
13676 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13677 return _PyUnicodeWriter_WriteStr(writer, str);
13678
13679 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13680 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13681 else
13682 maxchar = writer->maxchar;
13683 len = end - start;
13684
13685 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13686 return -1;
13687
13688 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13689 str, start, len);
13690 writer->pos += len;
13691 return 0;
13692}
13693
13694int
Victor Stinner4a587072013-11-19 12:54:53 +010013695_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13696 const char *ascii, Py_ssize_t len)
13697{
13698 if (len == -1)
13699 len = strlen(ascii);
13700
13701 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13702
13703 if (writer->buffer == NULL && !writer->overallocate) {
13704 PyObject *str;
13705
13706 str = _PyUnicode_FromASCII(ascii, len);
13707 if (str == NULL)
13708 return -1;
13709
13710 writer->readonly = 1;
13711 writer->buffer = str;
13712 _PyUnicodeWriter_Update(writer);
13713 writer->pos += len;
13714 return 0;
13715 }
13716
13717 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13718 return -1;
13719
13720 switch (writer->kind)
13721 {
13722 case PyUnicode_1BYTE_KIND:
13723 {
13724 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13725 Py_UCS1 *data = writer->data;
13726
Christian Heimesf051e432016-09-13 20:22:02 +020013727 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013728 break;
13729 }
13730 case PyUnicode_2BYTE_KIND:
13731 {
13732 _PyUnicode_CONVERT_BYTES(
13733 Py_UCS1, Py_UCS2,
13734 ascii, ascii + len,
13735 (Py_UCS2 *)writer->data + writer->pos);
13736 break;
13737 }
13738 case PyUnicode_4BYTE_KIND:
13739 {
13740 _PyUnicode_CONVERT_BYTES(
13741 Py_UCS1, Py_UCS4,
13742 ascii, ascii + len,
13743 (Py_UCS4 *)writer->data + writer->pos);
13744 break;
13745 }
13746 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013747 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013748 }
13749
13750 writer->pos += len;
13751 return 0;
13752}
13753
13754int
13755_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13756 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013757{
13758 Py_UCS4 maxchar;
13759
13760 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13761 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13762 return -1;
13763 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13764 writer->pos += len;
13765 return 0;
13766}
13767
Victor Stinnerd3f08822012-05-29 12:57:52 +020013768PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013769_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013770{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013771 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013772
Victor Stinnerd3f08822012-05-29 12:57:52 +020013773 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013774 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013775 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013776 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013777
13778 str = writer->buffer;
13779 writer->buffer = NULL;
13780
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013781 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013782 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13783 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013784 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013785
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013786 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13787 PyObject *str2;
13788 str2 = resize_compact(str, writer->pos);
13789 if (str2 == NULL) {
13790 Py_DECREF(str);
13791 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013792 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013793 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013794 }
13795
Victor Stinner15a0bd32013-07-08 22:29:55 +020013796 assert(_PyUnicode_CheckConsistency(str, 1));
13797 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013798}
13799
Victor Stinnerd3f08822012-05-29 12:57:52 +020013800void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013801_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013802{
13803 Py_CLEAR(writer->buffer);
13804}
13805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013807
13808PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013809 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013810\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013811Return a formatted version of S, using substitutions from args and kwargs.\n\
13812The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013813
Eric Smith27bbca62010-11-04 17:06:58 +000013814PyDoc_STRVAR(format_map__doc__,
13815 "S.format_map(mapping) -> str\n\
13816\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013817Return a formatted version of S, using substitutions from mapping.\n\
13818The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013819
INADA Naoki3ae20562017-01-16 20:41:20 +090013820/*[clinic input]
13821str.__format__ as unicode___format__
13822
13823 format_spec: unicode
13824 /
13825
13826Return a formatted version of the string as described by format_spec.
13827[clinic start generated code]*/
13828
Eric Smith4a7d76d2008-05-30 18:10:19 +000013829static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013830unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013831/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013832{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013833 _PyUnicodeWriter writer;
13834 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013835
Victor Stinnerd3f08822012-05-29 12:57:52 +020013836 if (PyUnicode_READY(self) == -1)
13837 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013838 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013839 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13840 self, format_spec, 0,
13841 PyUnicode_GET_LENGTH(format_spec));
13842 if (ret == -1) {
13843 _PyUnicodeWriter_Dealloc(&writer);
13844 return NULL;
13845 }
13846 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013847}
13848
INADA Naoki3ae20562017-01-16 20:41:20 +090013849/*[clinic input]
13850str.__sizeof__ as unicode_sizeof
13851
13852Return the size of the string in memory, in bytes.
13853[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013854
13855static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013856unicode_sizeof_impl(PyObject *self)
13857/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013859 Py_ssize_t size;
13860
13861 /* If it's a compact object, account for base structure +
13862 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013863 if (PyUnicode_IS_COMPACT_ASCII(self))
13864 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13865 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013866 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013867 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013868 else {
13869 /* If it is a two-block object, account for base object, and
13870 for character block if present. */
13871 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013872 if (_PyUnicode_DATA_ANY(self))
13873 size += (PyUnicode_GET_LENGTH(self) + 1) *
13874 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013875 }
13876 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013877 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013878 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13879 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13880 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13881 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013882
13883 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013884}
13885
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013886static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013887unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013888{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013889 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013890 if (!copy)
13891 return NULL;
13892 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013893}
13894
Guido van Rossumd57fd912000-03-10 22:53:23 +000013895static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013896 UNICODE_ENCODE_METHODDEF
13897 UNICODE_REPLACE_METHODDEF
13898 UNICODE_SPLIT_METHODDEF
13899 UNICODE_RSPLIT_METHODDEF
13900 UNICODE_JOIN_METHODDEF
13901 UNICODE_CAPITALIZE_METHODDEF
13902 UNICODE_CASEFOLD_METHODDEF
13903 UNICODE_TITLE_METHODDEF
13904 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013905 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013906 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013907 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013908 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013909 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013910 UNICODE_LJUST_METHODDEF
13911 UNICODE_LOWER_METHODDEF
13912 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013913 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13914 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013915 UNICODE_RJUST_METHODDEF
13916 UNICODE_RSTRIP_METHODDEF
13917 UNICODE_RPARTITION_METHODDEF
13918 UNICODE_SPLITLINES_METHODDEF
13919 UNICODE_STRIP_METHODDEF
13920 UNICODE_SWAPCASE_METHODDEF
13921 UNICODE_TRANSLATE_METHODDEF
13922 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013923 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13924 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013925 UNICODE_ISASCII_METHODDEF
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